跳到主要内容

$.ajax

$.ajax(options) ⇒ XMLHttpRequest

Perform an Ajax request. It can be to a local resource, or cross-domain via HTTP access control support in browsers or JSONP.

Options:

  • type (default: "GET"): HTTP request method ("GET", "POST", or other)
  • url (default: current URL): URL to which the request is made
  • data (default: none): data for the request; for GET requests it is appended to query string of the URL. Non-string objects will get serialized with $.param
  • processData (default: true): whether to automatically serialize data for non-GET requests to string
  • contentType (default: "application/x-www-form-urlencoded"): the Content-Type of the data being posted to the server (this can also be set via headers). Pass false to skip setting the default value.
  • mimeType (default: none): override the MIME type of the response. v1.1+
  • dataType (default: none): response type to expect from the server. One of json, jsonp, script, xml, html, or text.
  • jsonp (default: "callback"): the name of the JSONP callback query parameter
  • jsonpCallback (default: "jsonp{N}"): the string (or a function that returns) name of the global JSONP callback function. Set this to enable browser caching. v1.1+
  • timeout (default: 0): request timeout in milliseconds, 0 for no timeout
  • headers: object of additional HTTP headers for the Ajax request
  • async (default: true): set to false to issue a synchronous (blocking) request
  • global (default: true): trigger global Ajax events on this request
  • context (default: window): context to execute callbacks in
  • traditional (default: false): activate traditional (shallow) serialization of data parameters with $.param
  • cache (default: true): whether the browser should be allowed to cache GET responses. Since v1.1.4, the default is false for dataType: "script" or jsonp.
  • xhrFields (default: none): an object containing properties to be copied over verbatim to the XMLHttpRequest instance. v1.1+
  • username & password (default: none): HTTP Basic authentication credentials. v1.1+

If the URL contains =? or dataType is "jsonp", the request is performed by injecting a <script> tag instead of using XMLHttpRequest (see JSONP). This has the limitation of contentType, dataType, headers, and async not being supported.

Ajax callbacks​

You can specify the following callback functions, which are given in order of execution:

  1. beforeSend(xhr, settings): before the request is sent. Provides access to the xhr object and allows changing the settings. Return false from the function to cancel the request

  2. success(data, status, xhr): when request succeeds

  3. error(xhr, errorType, error): if there is an error (timeout, parse error, or status code not in HTTP 2xx)

  4. complete(xhr, status): after the request is complete, regardless of error or success

Promise callback interface v1.1+​

If the optional modules "callbacks" and "deferred" are loaded, the XHR object returned from $.ajax() calls implements a promise interface for adding callbacks by chaining:

xhr.done(function(data, status, xhr){ ... })
xhr.fail(function(xhr, errorType, error){ ... })
xhr.always(function(){ ... })
xhr.then(function(){ ... })

These methods supersede the success, error, and complete callback options.

Ajax events​

These events are fired during the lifecycle of an Ajax request performed with the default setting of global: true:

  1. ajaxStart (global): fired if no other Ajax requests are currently active

  2. ajaxBeforeSend (xhr, options): before sending the request; can be cancelled

  3. ajaxSend (xhr, options): like ajaxBeforeSend, but not cancellable

  4. ajaxSuccess (xhr, options, data): when the response is success

  5. ajaxError (xhr, options, error): when there was an error

  6. ajaxComplete (xhr, options): after request has completed, regardless of error or success

  7. ajaxStop (global): fired if this was the last active Ajax request

By default, Ajax events are fired on the document object. However, if the context of a request is a DOM node, the events are fired on that node and will bubble up the DOM. The only exceptions to this are the global events ajaxStart & ajaxStop.

$(document).on('ajaxBeforeSend', function(e, xhr, options){
// This gets fired for every Ajax request performed on the page.
// The xhr object and $.ajax() options are available for editing.
// Return false to cancel this request.
})

$.ajax({
type: 'GET',
url: '/projects',
// data to be added to query string:
data: { name: 'Zepto.js' },
// type of data we are expecting in return:
dataType: 'json',
timeout: 300,
context: $('body'),
success: function(data){
// Supposing this JSON payload was received:
// {"project": {"id": 42, "html": "<div>..." }}
// append the HTML to context object.
this.append(data.project.html)
},
error: function(xhr, type){
alert('Ajax error!')
}
})

// post a JSON payload:
$.ajax({
type: 'POST',
url: '/projects',
// post payload:
data: JSON.stringify({ name: 'Zepto.js' }),
contentType: 'application/json'
})