jQuery ajax - ajax() method

Example

Load a segment of text via AJAX:

jQuery Code:

$(document).ready(function(){
  $("#b01").click(function(){
  htmlobj=$.ajax({url:"/jquery/test1.txt",async:false});
  $("#myDiv").html(htmlobj.responseText);
  });
});

HTML Code:

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button id="b01" type="button">Change Content</button>

Try It Yourself

Definition and Usage

The ajax() method loads remote data through HTTP requests.

This method is the underlying AJAX implementation of jQuery. For a simple and easy-to-use high-level implementation, see $.get, $.post, etc. The $.ajax() method returns the XMLHttpRequest object it creates. In most cases, you do not need to directly operate this function unless you need to operate less commonly used options to gain more flexibility.

In the simplest case, $.ajax() can be used directly without any parameters.

Note:All options can be globally set through the $.ajaxSetup() function.

Syntax

jQuery.ajax([settings)]}
Parameters Description
settings

Optional. A set of key-value pairs used to configure Ajax requests.

Any option can be set to its default value through $.ajaxSetup().

Parameters

options

Type: Object

Optional. AJAX request settings. All options are optional.

async

Type: Boolean

Default value: true. Under the default settings, all requests are asynchronous. If you need to send a synchronous request, please set this option to false.

Note that synchronous requests will lock the browser, and other user operations must wait for the request to complete before they can be executed.

beforeSend(XHR)

Type: Function

Functions that can modify the XMLHttpRequest object before sending the request, such as adding custom HTTP headers.

The XMLHttpRequest object is the only parameter.

This is an Ajax event. If it returns false, it can cancel this Ajax request.

cache

Type: Boolean

Default value: true, when dataType is script and jsonp, it defaults to false. Setting it to false will not cache this page.

jQuery 1.2 New Features.

complete(XHR, TS)

Type: Function

Callback function after request completion (called after the request is successful or failed).

Parameters: XMLHttpRequest object and a string describing the request type.

This is an Ajax event.

contentType

Type: String

Default value: "application/x-www-form-urlencoded". The content encoding type when sending information to the server.

The default value is suitable for most cases. If you explicitly pass a content-type to $.ajax(), it will definitely be sent to the server (even if there is no data to send).

context

Type: Object

This object is used to set the context of Ajax-related callback functions. That is, let the this inside the callback function point to this object (if this parameter is not set, then this points to the options parameter passed when calling this AJAX request). For example, specifying a DOM element as the context parameter, so that the context of the success callback function is set to this DOM element.

Like this:

$.ajax({ url: "test.html", context: document.body, success: function(){
        $(this).addClass("done");
      });
data

Type: String

Data sent to the server. It will be automatically converted to request string format. It will be appended to the URL in GET requests. Check the processData option description to disable this automatic conversion. It must be in Key/Value format. If it is an array, jQuery will automatically assign the same name to different values. For example, {foo:["bar1", "bar2"]} is converted to '&foo=bar1&foo=bar2'.

dataFilter

Type: Function

A function to preprocess the original data returned by Ajax. It provides two parameters: data is the original data returned by Ajax, and type is the dataType parameter provided when calling jQuery.ajax. The value returned by the function will be further processed by jQuery.

dataType

Type: String

The expected data type returned by the server. If not specified, jQuery will automatically judge intelligently according to the MIME information of the HTTP packet, for example, XML MIME type is recognized as XML. In version 1.4, JSON will generate a JavaScript object, and script will execute this script. Then the server-side data returned will be parsed according to this value and passed to the callback function. Available values:

  • "xml": Returns an XML document, which can be processed by jQuery.
  • "html": Returns plain text HTML information; the script tags contained will be executed when inserted into the dom.
  • "script": Returns plain text JavaScript code. The result will not be automatically cached unless the 'cache' parameter is set. Note: When making remote requests (not on the same domain), all POST requests will be converted to GET requests. (Because the DOM's script tag will be used to load)
  • "json": Returns JSON data.
  • "jsonp": JSONP format. When calling a function in JSONP format, such as 'myurl?callback=?', jQuery will automatically replace '?' with the correct function name to execute the callback function.
  • "text": Returns a plain text string
error

Type: Function

Default value: automatically judge (xml or html). Call this function when the request fails.

There are three parameters: XMLHttpRequest object, error information, (optional) caught exception object.

If an error occurs, the error information (the second parameter) in addition to getting null, may also be 'timeout', 'error', 'notmodified', and 'parsererror'.

This is an Ajax event.

global

Type: Boolean

Whether to trigger global AJAX events. Default value: true. Setting it to false will not trigger global AJAX events, such as 'ajaxStart' or 'ajaxStop' can be used to control different Ajax events.

ifModified

Type: Boolean

Fetch new data only when the server data changes. Default value: false. Use HTTP package Last-Modified header information to judge. In jQuery 1.4, it will also check the 'etag' specified by the server to determine that the data has not been modified.

jsonp

Type: String

Rewrite the name of the callback function in a jsonp request. This value is used to replace the 'callback' part in the URL parameter of GET or POST requests in the form of 'callback=?', such as {jsonp:'onJsonPLoad'} will cause 'onJsonPLoad=?' to be sent to the server.

jsonpCallback

Type: String

Specify a callback function name for jsonp requests. This value will be used to replace the random function name automatically generated by jQuery. This is mainly used to make jQuery generate unique function names, making it easier to manage requests and conveniently provide callback functions and error handling. You can also specify this callback function name when you want the browser to cache GET requests.

password

Type: String

Password used to respond to HTTP access authentication requests

processData

Type: Boolean

Default value: true. By default, if the data passed in through the data option is an object (technically, any that is not a string), it will be processed and converted into a query string to match the default content type "application/x-www-form-urlencoded". If you want to send DOM tree information or other information that you do not want to convert, set it to false.

scriptCharset

Type: String

It is only used to force modification of charset when dataType is "jsonp" or "script" and type is "GET". It is usually used when the content encoding of local and remote content is different.

success

Type: Function

Callback function after the request is successful.

Parameters: Data returned by the server and processed according to the dataType parameter; a string describing the status.

This is an Ajax event.

traditional

Type: Boolean

If you want to serialize data in the traditional way, set it to true. Refer to the jQuery.param method under the Tools category.

timeout

Type: Number

Set the request timeout time (milliseconds). This setting will override the global setting.

type

Type: String

Default value: "GET")). Request method ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but they are only supported by some browsers.

url

Type: String

Default value: current page address. The address to send the request to.

username

Type: String

Used for the username to respond to HTTP authentication requests.

xhr

Type: Function

An XMLHttpRequest object needs to be returned. By default, it is ActiveXObject in IE and XMLHttpRequest in other cases. It is used to rewrite or provide an enhanced XMLHttpRequest object. This parameter was not available before jQuery 1.3.

Callback functions

To process the data obtained from $.ajax(), you need to use callback functions: beforeSend, error, dataFilter, success, complete.

beforeSend

This is called before sending the request and takes an XMLHttpRequest as a parameter.

error

This is called when the request fails. It takes an XMLHttpRequest object, a string describing the error type, and an exception object (if any).

dataFilter

This is called after the request is successful. It takes the returned data and the value of the 'dataType' parameter. It must return new data (which may be processed) to be passed to the success callback function.

success

This is called after the request. It takes the returned data and a string containing a success code.

complete

This function is called after the request is completed, regardless of success or failure. It takes an XMLHttpRequest object and a string containing a success or error code.

Data type

The $.ajax() function depends on the information provided by the server to process the returned data. If the server reports that the returned data is XML, the result can be traversed using ordinary XML methods or jQuery selectors. If other types are detected, such as HTML, the data is treated as text.

The dataType option can also specify other data processing methods. In addition to plain XML, it can also specify html, json, jsonp, script, or text.

For the 'text' and 'xml' types, the returned data is not processed. The data is simply passed to the success callback function via the XMLHttpRequest's responseText or responseHTML property.

Note:We must ensure that the MIME type reported by the web server matches the dataType we have chosen. For example, if XML is used, the server must declare 'text/xml' or 'application/xml' to obtain consistent results.

If specified as the 'html' type, any embedded JavaScript will be executed before the HTML is returned as a string. Similarly, if the 'script' type is specified, the server-side generated JavaScript will be executed first, and then the script will be returned as text data.

If specified as json type, the received data will be parsed as a JavaScript object, and the constructed object will be returned as the result. To achieve this, it first tries to use JSON.parse(). If the browser does not support it, a function is used to construct it.

JSON data is a structured data format that can be easily parsed through JavaScript. If the data file is stored on a remote server (different domain, also known as cross-domain data retrieval), the jsonp type must be used. When using this type, a query string parameter callback=? is created, which is added to the end of the request URL. The server should prefix the JSON data with the callback function name to complete an effective JSONP request. If you want to specify the parameter name for the callback function instead of the default callback, you can set the 'jsonp' parameter of $.ajax().

Note:JSONP is an extension of the JSON format. It requires some server-side code to detect and handle query string parameters.

If the script or jsonp type is specified, then when data is received from the server, it is actually used with the <script> tag instead of the XMLHttpRequest object. In this case, $.ajax() no longer returns an XMLHttpRequest object, and event handlers such as beforeSend are not passed.

Sending data to the server

By default, Ajax requests use the GET method. To use the POST method, you can set the 'type' parameter value. This option also affects how the content of the 'data' option is sent to the server.

The 'data' option can include a query string, such as key1=value1&key2=value2, or a map, such as {key1: 'value1', key2: 'value2'}. If the latter form is used, the data will be converted to a query string on the sender side. This process can also be bypassed by setting the 'processData' option to false. If we want to send an XML object to the server, this processing may not be appropriate, and in this case, we should also change the 'contentType' option to use other appropriate MIME types instead of the default application/x-www-form-urlencoded.

Advanced Options

The global option is used to prevent the response registration callback functions, such as .ajaxSend, or ajaxError, and similar methods. This is sometimes very useful, such as when sending requests very frequently and briefly, you can disable this in ajaxSend.

If the server requires HTTP authentication, the username and password can be set through the username and password options.

Ajax requests are time-limited, so error warnings can be captured and processed to improve user experience. The timeout parameter usually retains its default value, or is set globally through jQuery.ajaxSetup, rarely re-set for specific requests.

By default, the request will always be sent out, but the browser may retrieve data from its cache. To prevent the use of cached results, you can set the cache parameter to false. If you want to report an error when the data has not changed since the last request, you can set ifModified to true.

scriptCharset allows the request for the <script> tag to set a specific character set for script or jsonp-like data. This is especially useful when the script and page character sets are different.

The first letter of Ajax is the initial letter of asynchronous, which means that all operations are parallel and there is no order of completion. The async parameter of $.ajax() is always set to true, indicating that other code can still be executed after the request starts. It is strongly recommended not to set this option to false, which means that all requests will no longer be asynchronous, which may also cause the browser to be locked up.

$.ajax function returns the XMLHttpRequest object it creates. jQuery usually handles and creates this object internally, but users can also pass a self-created xhr object through the xhr option. The returned object is usually discarded, but still provides a low-level interface to observe and control the request. For example, calling .abort() on the object can suspend the request before it is completed.