Jquery 一个简单的hello world,介绍如何在JSON/AJAX中在客户端html和vb.net服务器之间交换数据
花了这么多天寻找一个解决方案,我留下的选择,但请你们在这里。我对AJAX完全陌生,并且不惜一切代价试图避免它,但这次,我别无选择,只能正视它 我想要的是HTML页面和服务器端ASPX页面(最好是VB)之间的简单数据交换(如hello world)。。我在网上看到的解决方案要么太复杂,我无法理解,要么是不完整的 我能够在aspx服务器应用程序中接收来自ajaxhtml页面的数据,但发现很难通过JSON-ajax与页面反馈信息。谢谢你的帮助。谢谢 我当前的客户端JQuery代码(如果是从我正在使用的教程中获得的) 我有一个联系人提交表单,当点击提交按钮时,它会调用下面的脚本。我在服务器端收到了用户的数据,但无法从服务器端向客户端页面发送成功信号Jquery 一个简单的hello world,介绍如何在JSON/AJAX中在客户端html和vb.net服务器之间交换数据,jquery,asp.net,json,ajax,vb.net,Jquery,Asp.net,Json,Ajax,Vb.net,花了这么多天寻找一个解决方案,我留下的选择,但请你们在这里。我对AJAX完全陌生,并且不惜一切代价试图避免它,但这次,我别无选择,只能正视它 我想要的是HTML页面和服务器端ASPX页面(最好是VB)之间的简单数据交换(如hello world)。。我在网上看到的解决方案要么太复杂,我无法理解,要么是不完整的 我能够在aspx服务器应用程序中接收来自ajaxhtml页面的数据,但发现很难通过JSON-ajax与页面反馈信息。谢谢你的帮助。谢谢 我当前的客户端JQuery代码(如果是从我正在使用的
<script>
(function($) {
'use strict';
/*
Contact Form: Basic
*/
$('#contactForm').validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $('#contactSuccess'),
$messageError = $('#contactError'),
$submitButton = $(this.submitButton),
$errorMessage = $('#mailErrorMessage');
$submitButton.button('loading');
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: {
Fname: $form.find('#Fname').val(),
Sname: $form.find('#Sname').val(),
GSM: $form.find('#GSM').val(),
sector: $form.find('#sector').val(),
email: $form.find('#email').val(),
categoryofclient: $form.find('#categoryofclient').val(),
message: $form.find('#message').val()
}
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
$messageSuccess.removeClass('hidden');
$messageError.addClass('hidden');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-error')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 180) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 180
}, 300);
}
$submitButton.button('reset');
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('hidden');
$messageSuccess.addClass('hidden');
if (($messageError.offset().top - 180) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 180
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.button('reset');
});
}
});
}).apply(this, [jQuery]);
</script>
当我运行ASPX页面时,我得到
{"response":"success"}
但它仍然无法触发客户端表单
ASPX/HTML标记
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="amasico.aspx.vb" Inherits="utilityserverapps._Default" %>
整个客户端HTML标记(指向某些CSS的链接位于其他位置)
联系我们
-
-
-
(123) 456-789
-
-
-
-
-
-
-
-
- 雇佣AMASICO
雇用阿马西科
了解我们如何为您服务?
成功您的邮件已发送给我们。
谢谢,我们很快就会给您打电话的!)
错误发送邮件时出错。
名字*
姓*
您的GSM号码*
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="amasico.aspx.vb" Inherits="utilityserverapps._Default" %>
<!DOCTYPE html>
<html>
<head>
<!-- Basic -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Contact Us </title>
<meta name="keywords" content="HTML5 Template" />
<meta name="description" content="Porto - Responsive HTML5 Template">
<meta name="author" content="okler.net">
<!-- Favicon -->
<link rel="shortcut icon" href="webcom/img/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="webcom/img/apple-touch-icon.png">
<!-- Mobile Metas -->
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Web Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800%7CShadows+Into+Light" rel="stylesheet" type="text/css">
<!-- Vendor CSS -->
<link rel="stylesheet" href="webcom/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="webcom/vendor/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="webcom/vendor/simple-line-icons/css/simple-line-icons.min.css">
<link rel="stylesheet" href="webcom/vendor/owl.carousel/assets/owl.carousel.min.css">
<link rel="stylesheet" href="webcom/vendor/owl.carousel/assets/owl.theme.default.min.css">
<link rel="stylesheet" href="webcom/vendor/magnific-popup/magnific-popup.min.css">
<!-- Theme CSS -->
<link rel="stylesheet" href="webcom/css/theme.css">
<link rel="stylesheet" href="webcom/css/theme-elements.css">
<link rel="stylesheet" href="webcom/css/theme-blog.css">
<link rel="stylesheet" href="webcom/css/theme-shop.css">
<link rel="stylesheet" href="webcom/css/theme-animate.css">
<!-- Skin CSS -->
<link rel="stylesheet" href="webcom/css/skins/default.css">
<!-- Theme Custom CSS -->
<link rel="stylesheet" href="webcom/css/custom.css">
<!-- Head Libs -->
<script src="webcom/vendor/modernizr/modernizr.min.js"></script>
</head>
<body>
<div class="body">
<header id="header" data-plugin-options='{"stickyEnabled": true, "stickyEnableOnBoxed": true, "stickyEnableOnMobile": true, "stickyStartAt": 57, "stickySetTop": "-57px", "stickyChangeLogo": true}'>
<div class="header-body">
<div class="header-container container">
<div class="header-row">
<div class="header-column">
<div class="header-logo">
<a href="webcom/index.html">
<img alt="Amasico" width="200" height="70" data-sticky-width="142" data-sticky-height="50" data-sticky-top="33" src="img/amalogo.jpg">
</a>
</div>
</div>
<div class="header-column">
<div class="header-row">
<nav class="header-nav-top">
<ul class="nav nav-pills">
<li class="hidden-xs">
<a href="webcom/about-us.html"><i class="fa fa-angle-right"></i> About Us</a>
</li>
<li class="hidden-xs">
<a href="webcom/contact-us.html"><i class="fa fa-angle-right"></i> Contact Us</a>
</li>
<li>
<span class="ws-nowrap"><i class="fa fa-phone"></i> (123) 456-789</span>
</li>
</ul>
</nav>
</div>
<div class="header-row">
<div class="header-nav">
<button class="btn header-btn-collapse-nav" data-toggle="collapse" data-target=".header-nav-main">
<i class="fa fa-bars"></i>
</button>
<ul class="header-social-icons social-icons hidden-xs">
<li class="social-icons-facebook"><a href="http://www.facebook.com/" target="_blank" title="Facebook"><i class="fa fa-facebook"></i></a>
</li>
<li class="social-icons-twitter"><a href="http://www.twitter.com/" target="_blank" title="Twitter"><i class="fa fa-twitter"></i></a>
</li>
<li class="social-icons-linkedin"><a href="http://www.linkedin.com/" target="_blank" title="Linkedin"><i class="fa fa-linkedin"></i></a>
</li>
</ul>
<div class="header-nav-main header-nav-main-effect-1 header-nav-main-sub-effect-1 collapse">
<nav>
<ul class="nav nav-pills" id="mainNav">
<li>
<a href="index.html">
Home
</a>
</li>
<li class="dropdown-mega active">
<a href="index.html">
About Us
</a>
</li>
<li>
<a href="index.html">
Products
</a>
</li>
<li>
<a href="index.html">
Services
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<div role="main" class="main">
<section class="page-header">
<div class="container">
<div class="row">
<div class="col-md-12">
<ul class="breadcrumb">
<li><a href="#">Home</a>
</li>
<li class="active">HIRE AMASICO</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h1>HIRE AMASICO</h1>
</div>
</div>
</div>
</section>
<div class="container">
<div class="row">
<div class="col-md-3"><img src="img/contactus.jpg" class="img-responsive" alt="Contact us" />
</div>
<div class="col-md-6">
<h2 class="mb-sm mt-sm"><strong>Discover </strong>how we can serve you?</h2>
<br>
<br>
<div class="alert alert-success hidden mt-lg" id="contactSuccess">
<strong>Success!</strong> Your message has been sent to us.
<br> Thank you, we will call you soon!) </div>
<div class="alert alert-danger hidden mt-lg" id="contactError">
<strong>Error!</strong> There was an error sending your message.
<span class="font-size-xs mt-sm display-block" id="mailErrorMessage"></span>
</div>
<form id="contactForm" action="http://localhost:57414/amasico.aspx" method="POST">
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>First Name *</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="Fname" id="Fname" required>
</div>
<div class="col-md-6">
<label>Surname *</label>
<input type="text" value="" data-msg-required="Please enter your surname." maxlength="100" class="form-control" name="Sname" id="Sname" required>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Your GSM Number *</label>
<input type="telephone" value="" data-msg-required="Please enter your GSM no." maxlength="100" class="form-control" name="GSM" id="GSM" required placeholder="GSM number">
</div>
<div class="col-md-6">
<label>Your email address *</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="col-md-12 control-label">Category</label>
<div class="col-md-6">
<select name="categoryofclient" class="form-control" id="categoryofclient" data-plugin-selectTwo>
<option value="SELF_EMPLOYED">SELF EMPLOYED </option>
<option value="ENTREPRENEUR">ENTREPRENEUR</option>
<option value="EMPLOYED">EMPLOYED </option>
<option value="UNEMPLOYED">UNEMPLOYED</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Industrial Sector</label>
<input type="text" value="" data-msg-required="Please enter the sector you are interested in." maxlength="100" class="form-control" name="sector" id="sector" required>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Other comment? *</label>
<textarea maxlength="3000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" data-loading-text="Loading...">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<footer id="footer">
<div class="container">
<div class="row">
<div class="footer-ribbon">
<span>Get in Touch</span>
</div>
<div class="col-md-6">
<div class="contact-details">
<h4>Contact Us</h4>
<ul class="contact">
<li>
<p><i class="fa fa-map-marker"></i> <strong>Address:</strong> 1234 Street Name, City Name, United States</p>
</li>
<li>
<p><i class="fa fa-phone"></i> <strong>Phone:</strong> (123) 456-789</p>
</li>
<li>
<p><i class="fa fa-envelope"></i> <strong>Email:</strong> <a href="mailto:mail@example.com">mail@example.com</a>
</p>
</li>
</ul>
</div>
</div>
<div class="col-md-2">
<h4>Follow Us</h4>
<ul class="social-icons">
<li class="social-icons-facebook"><a href="http://www.facebook.com/" target="_blank" title="Facebook"><i class="fa fa-facebook"></i></a>
</li>
<li class="social-icons-twitter"><a href="http://www.twitter.com/" target="_blank" title="Twitter"><i class="fa fa-twitter"></i></a>
</li>
<li class="social-icons-linkedin"><a href="http://www.linkedin.com/" target="_blank" title="Linkedin"><i class="fa fa-linkedin"></i></a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
<div class="row">
<div class="col-md-1">
<a href="index.html" class="logo">
<img src="img/amalogoBlack.jpg" alt="Amasico Freelance" width="200" height="70" class="img-responsive">
</a>
</div>
<div class="col-md-7">
<p>© Copyright 2016. All Rights Reserved.</p>
</div>
<div class="col-md-4">
<nav id="sub-menu">
<ul>
<li><a href="page-faq.html">FAQ's</a>
</li>
<li><a href="sitemap.html">Sitemap</a>
</li>
<li><a href="contact-us.html">Contact</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</footer>
</div>
<!-- Vendor -->
<script src="webcom/vendor/jquery/jquery.min.js"></script>
<script src="webcom/vendor/jquery.appear/jquery.appear.min.js"></script>
<script src="webcom/vendor/jquery.easing/jquery.easing.min.js"></script>
<script src="webcom/vendor/jquery-cookie/jquery-cookie.min.js"></script>
<script src="webcom/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="webcom/vendor/common/common.min.js"></script>
<script src="webcom/vendor/jquery.validation/jquery.validation.min.js"></script>
<script src="webcom/vendor/jquery.stellar/jquery.stellar.min.js"></script>
<script src="webcom/vendor/jquery.easy-pie-chart/jquery.easy-pie-chart.min.js"></script>
<script src="webcom/vendor/jquery.gmap/jquery.gmap.min.js"></script>
<script src="webcom/vendor/jquery.lazyload/jquery.lazyload.min.js"></script>
<script src="webcom/vendor/isotope/jquery.isotope.min.js"></script>
<script src="webcom/vendor/owl.carousel/owl.carousel.min.js"></script>
<script src="webcom/vendor/magnific-popup/jquery.magnific-popup.min.js"></script>
<script src="webcom/vendor/vide/vide.min.js"></script>
<!-- Theme Base, Components and Settings -->
<script src="webcom/js/theme.js"></script>
<!-- Current Page Vendor and Views -->
<script>
(function($) {
'use strict';
/*
Contact Form: Basic
*/
$('#contactForm').validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $('#contactSuccess'),
$messageError = $('#contactError'),
$submitButton = $(this.submitButton),
$errorMessage = $('#mailErrorMessage');
$submitButton.button('loading');
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: {
Fname: $form.find('#Fname').val(),
Sname: $form.find('#Sname').val(),
GSM: $form.find('#GSM').val(),
sector: $form.find('#sector').val(),
email: $form.find('#email').val(),
categoryofclient: $form.find('#categoryofclient').val(),
message: $form.find('#message').val()
}
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
$messageSuccess.removeClass('hidden');
$messageError.addClass('hidden');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-error')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 180) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 180
}, 300);
}
$submitButton.button('reset');
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('hidden');
$messageSuccess.addClass('hidden');
if (($messageError.offset().top - 180) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 180
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.button('reset');
});
}
});
/*
Contact Form: Advanced
*/
$('#contactFormAdvanced').validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
'captcha': {
captcha: true
},
'checkboxes[]': {
required: true
},
'radios': {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
error.appendTo(element.parent().parent());
} else {
error.insertAfter(element);
}
}
});
}).apply(this, [jQuery]);
</script>
<!-- Theme Custom -->
<script src="webcom/js/custom.js"></script>
<!-- Theme Initialization Files -->
<script src="webcom/js/theme.init.js"></script>
<script>
</body>
</html>
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
<Services.WebMethod()>
Public Shared Function Hello(name As String) As String
Return "hello " + name
End Function
End Class
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "webform1.aspx/Hello",
data: "{name:'Raj'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (msg) {
console.log("error:" + JSON.stringify(msg));
}
});
});
</script>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
<System.Web.Services.WebMethod()> _
Public Shared Function SubmitContactForm(ByVal data As ContactDetails) As String
'Do some data validation here - don't rely on client-side validation alone!
'do whatever you need to do to save the data, the at the end:
Return "{ 'response': 'success' }" 'Once this works, think about using a more formal structure like an object containing your response values (e.g. validation errors)
End Function
$("#contactForm").validate(function()
{
submitHandler: function(form) {
alert("about to submit form"); //just for testing :-)
var $form = $(form);
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "data": $form.serializeArray() }), //this should automatically grab all the fields from your form
success: function(response) { //ajax request succeeds
alert(response); //just for testing :-)
//do whatever else you need to with the response here.
},
error: function (jQXHR, textStatus, errorThrown) { //ajax request fails (i.e. a HTTP error, not a validation error)
alert("An error occurred whilst attempting to contact the server: " + jQXHR.status + " " + errorThrown);
}
});
});
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace JSONDemo
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class json : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string TestJSON()
{
Employee[] e = new Employee[2];
e[0] = new Employee();
e[0].Name = "Ajay Singh";
e[0].Company = "Birlasoft Ltd.";
e[0].Address = "LosAngeles California";
e[0].Phone = "1204675";
e[0].Country = "US";
e[1] = new Employee();
e[1].Name = "Ajay Singh";
e[1].Company = "Birlasoft Ltd.";
e[1].Address = "D-195 Sector Noida";
e[1].Phone = "1204675";
e[1].Country = "India";
feedback[] f2 = new feedback[1];
f2[0] = new feedback();
f2[0].response = "success";
return new JavaScriptSerializer().Serialize(e);
//Context.Response.Write(new JavaScriptSerializer().Serialize(e)); //returns text string
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void TestJSON2()
{
Employee[] e = new Employee[2];
e[0] = new Employee();
e[0].Name = "Ajay Singh";
e[0].Company = "Birlasoft Ltd.";
e[0].Address = "LosAngeles California";
e[0].Phone = "1204675";
e[0].Country = "US";
e[1] = new Employee();
e[1].Name = "Ajay Singh";
e[1].Company = "Birlasoft Ltd.";
e[1].Address = "D-195 Sector Noida";
e[1].Phone = "1204675";
e[1].Country = "India";
feedback[] f2 = new feedback[1];
f2[0] = new feedback();
f2[0].response = "success";
//return new JavaScriptSerializer().Serialize(e);
Context.Response.Write(new JavaScriptSerializer().Serialize(e)); //returns text string
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void FeedbackB()
{
feedback[] f2 = new feedback[1];
f2[0] = new feedback();
f2[0].response = "success";
//return new JavaScriptSerializer().Serialize(e);
Context.Response.Write(new JavaScriptSerializer().Serialize(f2)); //returns text string
}
[WebMethod]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string FeedbackC()
{
feedback[] f2 = new feedback[1];
f2[0] = new feedback();
f2[0].response = "success";
return new JavaScriptSerializer().Serialize(f2);
//Context.Response.Write(new JavaScriptSerializer().Serialize(f2)); //returns text string
}
[WebMethod]
public string FeedbackD()
{
var data = new { sresponse = "success"};
// We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below)
// SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName };
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(data);
}
[WebMethod]
public string SayHello(string firstName, string lastName)
{
return "Hello " + firstName + " " + lastName;
}
[WebMethod]
public string SayHelloJson(string firstName, string lastName)
{
var data = new { Greeting = "Hello", Name = firstName + " " + lastName };
// We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below)
// SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName };
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(data);
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public Employee[] TestXML()
{
Employee[] e = new Employee[2];
e[0] = new Employee();
e[0].Name = "Ajay Singh";
e[0].Company = "Birlasoft Ltd.";
e[0].Address = "LosAngeles California";
e[0].Phone = "310-235-1535";
e[0].Country = "US";
e[1] = new Employee();
e[1].Name = "Ajay Singh";
e[1].Company = "Birlasoft Ltd.";
e[1].Address = "D-195 Sector Noida";
e[1].Phone = "120-467500";
e[1].Country = "India";
return e;
}
}
}
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
public class Employee
{
public string Name { get; set; }
public string Company { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Country { get; set; }
}
public class feedback
{
public string response { get; set; }
}
public class SayHello
{
public string Greeting { get; set; }
public string Name { get; set; }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<script src="jquery-2.js"></script>
<form id="form1" runat="server">
<div>
<div><br />Example A</div>
<div id="searchresultsA"></div>
<div><br />Example B</div>
<div id="searchresultsB"></div>
<div><br />Example C</div>
<div id="searchresultsC"></div>
<div><br />Example D</div>
<div id="searchresultsD"></div>
<div><br />Example E</div>
<div id="searchresultsE"></div>
</div>
</form>
</body>
<script type="text/javascript">
$(document).ready(function () {
// Example A - call a function that returns a string.
// Params are sent as form-encoded, data that comes back is text
$.ajax({
type: "POST",
url: "http://localhost:65039/json.asmx/TestJSON",
data: "firstName=Aidy&lastName=F", // the data in form-encoded format, ie as it would appear on a querystring
//contentType: "application/x-www-form-urlencoded; charset=UTF-8", // if you are using form encoding, this is default so you don't need to supply it
dataType: "text", // the data type we want back, so text. The data will come wrapped in xml
success: function (data) {
$("#searchresultsA").html(data); // show the string that was returned, this will be the data inside the xml wrapper
}
});
$.ajax({
type: "POST",
url: "http://localhost:65039/json.asmx/SayHello",
data: "{firstName:'Aidy', lastName:'F'}", // the data in JSON format. Note it is *not* a JSON object, is is a literal string in JSON format
contentType: "application/json; charset=utf-8", // we are sending in JSON format so we need to specify this
dataType: "json", // the data type we want back. The data will come back in JSON format
success: function (data) {
$("#searchresultsB").html(data.d); // it's a quirk, but the JSON data comes back in a property called "d"; {"d":"Hello Aidy F"}
}
});
$.ajax({
type: "POST",
url: "http://localhost:65039/json.asmx/TestJSON",
data: { firstName: 'Aidy', lastName: 'F' }, // here we are specifing the data as a JSON object, not a string in JSON format
// this will be converted into a form encoded format by jQuery
// even though data is a JSON object, jQuery will convert it to "firstName=Aidy&lastName=F" so it *is* form encoded
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "text", // the data type we want back, so text. The data will come wrapped in xml
success: function (data) {
$("#searchresultsC").html(data); // show the data inside the xml wrapper
}
});
$.ajax({
type: "POST",
url: "http://localhost:65039/json.asmx/SayHelloJson",
data: "{ firstName: 'Aidy', lastName: 'F' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = JSON.parse(data.d); // data.d is a JSON formatted string, to turn it into a JSON object
// we use JSON.parse
// now that myData is a JSON object we can access its properties like normal
$("#searchresultsD").html(myData.Greeting + " " + myData.Name);
}
});
$.ajax({
type: "POST",
url: "http://localhost:65039/json.asmx/FeedbackD",
data: "{ firstName: 'Aidy', lastName: 'F' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = JSON.parse(data.d); // data.d is a JSON formatted string, to turn it into a JSON object
// we use JSON.parse
// now that myData is a JSON object we can access its properties like normal
$("#searchresultsE").html(myData.sresponse);
}
});
});
</script>
</html>
Example A
[{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"LosAngeles California","Phone":"1204675","Country":"US"},{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"D-195 Sector Noida","Phone":"1204675","Country":"India"}]
Example B
Hello Aidy F
Example C
[{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"LosAngeles California","Phone":"1204675","Country":"US"},{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"D-195 Sector Noida","Phone":"1204675","Country":"India"}]
Example D
Hello Aidy F
Example E
success