日期:2014-05-16  浏览次数:20601 次

ajax学习笔记(五)

jquery除了提供getpost请求交互外,提供了一个极其强大和灵活的调用方式$.ajax(),通过设置此函数的具体参数对象信息,可以实现各种的调用方式和返回信息。

Load a remote page using an HTTP request.
This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but

don't offer as much functionality (such as error callbacks).
$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to

abort the request manually.

Note: If you specify the dataType option described below, make sure the server sends the correct MIME type in the response (eg. xml as "text/xml").

Sending the wrong MIME type can lead to unexpected problems in your script. See Specifying the Data Type for AJAX Requests for more information.

$.ajax() takes one argument, an object of key/value pairs, that are used to initialize and handle the request. See below for a full list of the key/values

that can be used.

As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery

automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will

be automatically added to your Ajax request.

???? $.ajax({
??????
url:"test",
?????? type:"Post",
?????? success:back,
?????? dataType:"xml",
?????? data: "name="+userName
?? }) ;

?????? 调用成功后jquery会自动调用回调函数,我们可以获取服务器端返回的xml数据,为了处理xml数据,要先将数据转换成jquery的对象,然后通过jquery提供的筛选函数

jquery对象属性获取所需的文本内容。

find(expr)

Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.
All searching is done using a jQuery expression. The expression can be written using CSS 1-3 Selector syntax.
text()

Get the text contents of all matched elements.
The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents.
回调函数

function back(result){
??? var messageNode=$(result).find("message");
??? var messageString=messageNode.text();
??? var resultNode=$("#result");
??? resultNode.html(messageString);
}

AJAX详细参数设置

async (Boolean) : (默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必

须等待请求完成才可以执行。

beforeSend (Function) : 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。这是一个 Ajax 事件。如果返回

false可以取消本次ajax请求。

function (XMLHttpRequest) {
??? this; //
调用本次AJAX请求时传递的options参数

}
cache (Boolean