jQuery API jQuery API 中英文对照版 - jQuery在线查询手册
$.ajax(properties)

$.ajax(properties)

使用HTTP请求(XMLHttpRequest)载入一个远程页面。

这是jQuery的低级AJAX实现。要查看高级抽象,见$.set、$.post等。

$.ajax()返回创建好的XMLHttpRequest对象。多数情况下并不需要直接操纵这个对象,但是如果需要手动中止请求,它也是可用的。

注意:要确保服务器返回正确的MIME类型(例如:XML是“text/xml”)。如果返回了错误的MIME类型就会导致jQuery无法处理的严重问题。

支持的数据类型包括(见dataType选项):

"xml": 返回一个可以由jQuery对象处理的XML文档。

"html": 返回纯文本格式的HTML,包括求值后的脚本标记。

"script": 将响应作为Javascript语句求值,并返回纯文本。

"json": 将响应作为JSON求值,并返回一个Javascript对象。

$.ajax()带有一个参数--“名/值对”形式的一个对象,用于初始化和处理请求。以下就是可用的所有“名/值对”:

(String) url - 要将请求发送到的URL地址。

(String) type - 请求的类型 ("POST" 或 "GET"), 默认是 "GET"。

(String) dataType - 期望从服务器端返回的数据类型。无默认值:如果服务器返回XML,就将responseXML传递到回调函数,否则将resposeText传递到回调函数。

(Boolean) ifModified - 只有响应自上次请求后被修改过才承认是成功的请求。是通过检查头部的Last-Modified值实现的。默认值为false,即忽略 对部分的检查

(Number) timeout - 覆盖全局延迟的局部延迟,例如,在其他所有延迟经过1秒钟后,启动一个较长延迟的单独请求。有关全局延迟,见$.ajaxTimeout()。

(Boolean) global - 是否为当前的请求触发全局AJAX事件处理函数,默认值为true。设置为false可以防止触发像ajaxStart或ajaxStop这样的全局事件处理函数。

(Function) error - 当请求失败时调用的函数。这个函数会得到三个参数:XMLHttpRequest对象、一个描述所发生的错误类型的字符串和一个可选异常对象(如果有)。

(Function) success - 当请求成功时调用的函数。这个函数会得到一个参数:从服务器返回的数据(根据“dataType”进行了格式化)。

(Function) complete - 当请求完成时调用的函数。这个函数会得到两个参数:XMLHttpRequest对象和一个描述请求成功的类型的字符串。

(Object|String) data - 要发送到服务器的数据。如果还不是一个字符串,就自动轮换为一个查询字符串。即附加到GET请求的url后面的字符串。要防止自动处理见processData选项。

(String) contentType - 设置发送请求的content=type。默认值是 "application/x-www-form-urlencoded", 这个值能满足多数情况。

(Boolean) processData - 在默认的情况下,如果data选项传进的数据是一个对象而不是字符串,将会自动地被处理和转换成一个查询字符串,以适应默认的content-type--"application/x-www-form-urlencoded"。如果想发送DOMDocuments,就要把这个选项设置为false。

(Boolean) async - 在默认的情况下,所有请求都是以异步的方式发送的(值为true)。如果要使用同步方式,需要将此项设置为false。

(Function) beforeSend - 用于设置自定义头部等信息的预调用函数,接收一个唯一的参数--XMLHttpRequest对象。

返回值:XMLHttpRequest

参数:

  • properties (Map): Key/value pairs to initialize the request with.
 
示例:

载入并执行一个JavaScript文件。

$.ajax({
 type: "GET",
 url: "test.js",
 dataType:   "script" 
}) 
示例:

将数据保存到服务器,并在保存完成后通报用户。

$.ajax({
 type: "POST",
 url: "some.php",
 data:   "name=John&location=Boston",
 success: function(msg){ alert( "Data Saved: " +   msg ); } 
}); 
示例:

同步载入数据。当请求处于活动期间阻塞浏览器。如果必须同步载入数据,最好是通过其他手段来阻止用户的交互,而不是阻塞整个浏览器。

ar html = $.ajax({
 url: "some.php",
 async: false   
}).responseText; 
示例:

将一个XML文档作为数据发送到服务器。通过将processData选项设置为false,可以避免把自动把数据转换为字符串。

ar xmlDocument = [create xml document];
$.ajax({
 url:   "page.php",
 processData: false,
 data: xmlDocument,
 success: handleResponse   
}); 
 
$.ajax( properties )

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.

Options

$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request. These are all the key/values that can be used:

  • async (Boolean) - By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
  • beforeSend (Function) - A pre-callback to modify the XMLHttpRequest object before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument.
  • complete (Function) - A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.
  • contentType (String) - When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.
  • data (Object|String) - Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing.
  • dataType (String) - The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response. The available types (and the result passed as the first argument to your success callback) are:
    • "xml": Returns a XML document that can be processed via jQuery.
    • "html": Returns HTML as plain text; included script tags are evaluated.
    • "script": Evaluates the response as JavaScript and returns it as plain text.
    • "json": Evaluates the response as JSON and returns a JavaScript Object.
  • error (Function) - A function to be called if the request fails. The function gets passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred.
  • global (Boolean) - Whether to trigger global AJAX event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered.
  • ifModified (Boolean) - Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header.
  • processData (Boolean) - By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, or other non-processed data, set this option to false.
  • success (Function) - A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the 'dataType' parameter.
  • timeout (Number) - Set a local timeout in ms for the request. This will override the global timeout, if one is set via $.ajaxTimeout. For example, you could use this property to give a single request a longer timeout than all other requests that you've set to time out in one second. See $.ajaxTimeout() for global timeouts.
  • type (String) - The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
  • url (String) - The URL to request.

Return value: XMLHttpRequest
Parameters:

  • properties (Map): Key/value pairs to initialize the request with.
 

Example:

Load and execute a JavaScript file.

 $.ajax({
     type: "GET",
     url: "test.js", 
    dataType: "script"   
})  

Example:

Save some data to the server and notify the user once its complete.

 $.ajax({
     type: "POST",
     url: "some.php",
     data: "name=John&location=Boston",
     success: function(msg){       alert( "Data Saved: " + msg );     }   
});  

Example:

Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.

 var html = $.ajax({
    url: "some.php",
    async: false   
}).responseText;  

Example:

Sends an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented.

 var xmlDocument = [create xml document];   
 $.ajax({
     url: "page.php",
     processData: false,
     data: xmlDocument,
     success: handleResponse   
});