描述:执行一个异步的HTTP请求(Ajax)。
- version added: 1.5
- jQuery.ajax( String url, Map settings )
-
url 一个字符串,请求被发送到的URL。 settings 配置Ajax请求的键/值对集合。 所有的设置都是额外附加的。默认情况下,可以设置任何选项$.ajaxSetup()。下面的jQuery.ajax( settings )列出了所有的设置。 - version added: 1.0
- jQuery.ajax( Map settings )
-
settings 配置Ajax请求的键/值对集合。 所有的设置都是额外附加的。默认情况下,可以设置任何选项$.ajaxSetup()。
最简单的情况是$.ajax()
没有任何参数:
$.ajax();
注意:
默认设置可以通过使用全局设置 $.ajaxSetup()
函数。
The jqXHR Object
$.ajax({ url: 'http://fiddle.jshell.net/favicon.png', beforeSend: function( xhr ) { xhr.overrideMimeType( 'text/plain; charset=x-user-defined' ); }, success: function( data ) { if (console && console.log){ console.log( 'Sample of data:', data.slice(0,100) ); } } });
弃用公告:
jqXHR.success()
,jqXHR.error()
, 和jqXHR.complete()
回调将在jQuery 1.8被弃用。 请使用jqXHR.done()
,jqXHR.fail()
, 和jqXHR.always()
来替代。
// Assign handlers immediately after making the request, // and remember the jqxhr object for this request var jqxhr = $.ajax( "example.php" ) .done(function() { alert("success"); }) .fail(function() { alert("error"); }) .always(function() { alert("complete"); }); // perform other work here ... // Set another completion function for the request above jqxhr.always(function() { alert("second complete"); });
为了向后兼容 XMLHttpRequest
,jqXHR
对象使用下列属性和方法:
readyState
status
statusText
responseXML
and/orresponseText
,底层的请求回应xml或文本setRequestHeader(name, value)
which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old onegetAllResponseHeaders()
getResponseHeader()
abort()
No onreadystatechange
mechanism is provided,
however, since success
, error
,
complete
and statusCode
cover all
conceivable requirements.
Callback Function Queues
Here are the callback hooks provided by
$.ajax()
:
beforeSend
callback is invoked; it receives thejqXHR
object and thesettings
map as parameters.
For example, to make use of the returned HTML, we can implement
a success
handler:
$.ajax({ url: 'ajax/test.html', success: function(data) { $('.result').html(data); alert('Load was performed.'); } });
Data Types
Advanced Options
A workaround to this is possible by overriding
jQuery.ajaxSettings.xhr
as follows:
var _super = jQuery.ajaxSettings.xhr; jQuery.ajaxSettings.xhr = function () { var xhr = _super(), getAllResponseHeaders = xhr.getAllResponseHeaders; xhr.getAllResponseHeaders = function () { if ( getAllResponseHeaders() ) { return getAllResponseHeaders(); } var allHeaders = ""; $( ["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"] ).each(function (i, header_name) { if ( xhr.getResponseHeader( header_name ) ) { allHeaders += header_name + ": " + xhr.getResponseHeader( header_name ) + "\n"; } return allHeaders; }); }; return xhr; };
Extending Ajax
Examples:
-
例子:
保存一些数据到服务器并在完成时通知用户。 -
$.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", }).done(function( msg ) { alert( "Data Saved: " + msg ); });
-
例子:
检索一个HTML页面的最新版本。 -
$.ajax({ url: "test.html", cache: false, success: function(html){ $("#results").append(html); } });
-
例子:
发送一个xml文档给服务器。processData选项设置为false Send an xml document as data to the server. By setting the processData option tofalse
, the automatic conversion of data to strings is prevented. -
var xmlDocument = [create xml document]; var xmlRequest = $.ajax({ url: "page.php", processData: false, data: xmlDocument }); xmlRequest.done(handleResponse);
-
Example:
Send an id as data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert the user. -
var menuId = $("ul.nav").first().attr("id"); var request = $.ajax({ url: "script.php", type: "POST", data: {id : menuId}, dataType: "html" }); request.done(function(msg) { $("#log").html( msg ); }); request.fail(function(jqXHR, textStatus) { alert( "Request failed: " + textStatus ); });
-
例子:
加载并执行一个JavaScript文件。 -
$.ajax({ type: "GET", url: "test.js", dataType: "script" });