[ASP.NET]JQuery AJAX用法整理

摘要:[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);
}