AJAX 代表 Asynchronous Javascript And Xml ,其中的 Asynchronous 意味著不採行傳統 Postback 整個網頁表單送回伺服器的做法,而是透過 XmlHttpRequest 物件與伺服器溝通,再以 Javascript 解析伺服器端所傳回的資料。這種做法,避免了傳統Postback期間,網頁會歷經消失、等待、重新建立的過程,給予使用者更流暢的操作感受。
jQuery 對與後端溝通的相關作業提供了一系統的函數,其中最基層的函數叫做 $.ajax()。 它也有一系列的衍生函數,如 jQuery.get()、 jQuery.post()、 jQuery.getScript()、 jQuery.getJSON(),可以用更精簡的方法使用在特定的需求上。 通常這些方法以滿足大部份需求,除非你有需要進一步控制整個溝通細節,才需回頭使用 jQuery.ajax()。
Calling a Web Service with $.ajax()
The $.ajax() method enables you to call a web service and then update your page with the results. This method performs an asynchronous HTTP request, passes data to the request, and gets the results.
This method takes several name-value pairs as a parameter, called settings. The settings include the URL of your request, the content-type, the HTTP method (GET or POST), and the user name and password of the request. In fact, there are more than 20 settings with which you can work.
看範例先
如何使用 javascript 取得 server 上的資料
在使用 jQuery 呼叫 web service 之前,我們先來回顧一下如何使用 javascript 叫用 Web Service 。
如何使用 $.ajax() 方法取得 server 上的資料
如何使用 jQuery.get() 方法取得 server 上的資料
如何使用 .load() 方法取得 server 上的資料
使用 $.ajax() 叫用 Web Service
The $.ajax() method enables you to call a web service and then update your page with the results. This method takes several name-value pairs as a parameter, called settings. The settings include the URL of your request, the content-type, the HTTP method ...
$.ajax()的定義:
jQuery.ajax( url [, settings ] )
jQuery.ajax( [ settings ] )
其中的 settings 包括:
- url :Location of the service。
- type :要求的型態。[GET | POST | PUT | DELETE] verb
- contentType :傳送給 Server 的資料型態。[application/json | application/xml]
- dataType :預期 Server 回傳的資料型態。[json | xml]
- data :傳送給 Server 的資料。
- data :傳送給 Server 的資料。
- success :A function to be called if the request succeeds.
- error :A function to be called if the request fails.
- username :A username to be used in response to an HTTP access authentication request.
- password :A password to be used in response to an HTTP access authentication request.
底下,先來看個簡單例子:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string Hello(string name)
{
return "Hello " + name;
}
}
settings 是由 key/value 組成的集合,所有設定項目都是 optional,幾個項目的說明如下:(注意大小寫)
- url :指定要進行呼叫的位址
- type :請求方式,POST/GET。
- data :要傳給server的參數值,使用Key/value對,它為被附加在網址後頭
- contentType :傳送至Server的編碼類型 [application/json |application/xml ]
- dataType :預期Server傳回的資料類型,如果沒指定,jQuery會根據 HTTP MIME Type自動選擇以 responseXML 或 responseText 傳入你的 success callback。
- xml:
- html:
- script:
- json:
- jsonp:
- text:
- success :請求成功時執行函式。
- error :請求發生錯誤時執行函式。
- global
retrive xml data
XmlDocument xd = new XmlDocument();
xd.LoadXml(@"Name of first user first@contoso.com Name of second user second@contoso.com
");
Response.ContentType = "text/xml";
Response.Write(xd.OuterXml);
retrive json data
string data = "[{\"id\":\"first\" ,\"name\":\"vito\",\"email\":\"vito@gmail.com\"},";
data += "{\"id\":\"second\",\"name\":\"shao\",\"email\":\"shao@gmail.com\"}]";
Response.ContentType = "text/plain";
Response.Write(data);
使用 $.ajax() 叫用 WebPage
$.ajax() 方法,也可以用來叫用網頁中的方法,如此一來,你就不用特地再使用 web service 才能取得資料,而且叫用方法和上節一模一樣,
[WebMethod]
public static string Hello(string name)
{
return "Hello " + name + " \r\n" + DateTime.Now.ToString();
}
Notice that, in this case, you do not need to use the ScriptService attribute. ASP.NET assumes that code marked as a WebMethod inside a page is meant to be called from AJAX.
其他與 Ajax 相關的 jQuery 方法
The jQuery library exposes some additional jQuery methods that allow you to work with AJAX. These methods act as shorthand methods to the .ajax() method.
- jQuery.get():Load data from the server using a HTTP GET request.
- jQuery.post():Load data from the server using a HTTP POST request.
- jQuery.getScript():Load a JavaScript file from the server using a GET HTTP request, then execute it.
- jQuery.getJSON():Load JSON-encoded data from the server using a GET HTTP request.
- .load():Load data from the server and place the returned HTML into the matched element.
- .ajaxSend():Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.
- .ajaxSuccess():Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.
- .ajaxStart():Register a handler to be called when the first Ajax request begins. This is an Ajax Event.
- .ajaxStop():Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.
jQuery.get()
jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
Load data from the server using a HTTP GET request.
var url = "DataPage.aspx";
var param = "{'id': '1'}";
$.get(
url,
param,
function (result) { alert(result[0].name); },
"json");
jQuery.post()
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
Load data from the server using a HTTP POST request.
var url = "DataPage.aspx";
var param = "{'id': '1'}";
$.post(
url,
param,
function (result) { alert(result[0].name); },
"json");
.load()
.load( url [, data ] [, complete(responseText, textStatus, XMLHttpRequest) ] )
Load data from the server and place the returned HTML into the matched element.
var url = "DataPage.aspx";
var param = "{'id': '1'}";
$("#div1").load(url, param);