摘要:[ASP.NET] JQuery AJAX 用法整理
我们再用 Jquery CallBack Server 时有许多参数要如何使用
$.ajax({
type: "POST",
url: "MyWebService.asmx/SayHelloJson",
data: "{ firstName: 'Aidy', lastName: 'F' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = JSON.parse(data.d);
}
$.ajax({
type: "POST",
url: "MyWebService.asmx/SayHello",
data: "firstName=Aidy&lastName=F", /
dataType: "text",
success: function (data) {
$("#searchresultsA").html(data); /
}
});
Type :postback 给 server, Server 会 Respon 给 Client
Url: “MyWebService.asmx/SayHelloJson?firstName=’aidy’&lastName=’F’” 要注明方法 (Web Service)
传入参数,Server 端可以用 this.comtext.request.quertstring[“”] ,去取得 get 数据
“MyWebService.ahsx”(泛型处理常式)
“MyWebService.apsx”(一般网页)
Data: "{ firstName: 'Aidy', lastName: 'F' }" 可用 JSON 格式传入参数或是"firstName=Aidy&lastName=F"
Server 端用 this.comtext.request.From[“”],去取得 post 数据,
或是 Web Server 端会用 Fuction(string firstName, string lastName) 去取得 post 资
contentType: "application/json; charset=utf-8"如果是传送 data JSON 格式给 Server 要特别注明
dataType : "json","text",” xml”,Server 回传的数据型态
success : function (data){} :回传的数据跟动作
Web Server Code
[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);
}