jQuery.ajax()
function is used to load remote data through a background HTTP request .
jQuery.ajax()
The function is a jquery encapsulated Ajax technology implementation that allows us to retrieve data from a remote server without having to refresh the current page.
jQuery.ajax()
The function is the underlying AJAX implementation of jquery. Functions such as Jquery.get (), Jquery.post (), Load (), Jquery.getjson (), Jquery.getscript () are all simplified forms of the function (all call this function, except that the parameter settings differ or are omitted).
The function belongs jQuery
to a global object (also understood as a static function).
Grammar
JQuery 1.0 Adds this static function. jQuery.ajax()
There are two ways to use the function:
Jquery.ajax ([Settings]])
Jquery.ajax (URL [, Settings]])// usage two : JQuery 1.5 adds support for this usage.
Parameters
Find the corresponding parameter based on the parameter name defined in the previous syntax section .
Parameter settings
is an object that jQuery.ajax()
can recognize the following properties of the object (they are optional ):
Parameters |
Description |
Url |
string of type URL request. |
Settings |
The optional/object type is a single Object object, where each property is used to specify the additional parameter settings required to send the request. |
acceptsObject Type
Default value: Depends on the dataType
property.
Sends a Content-type request header that tells the server what type of response the browser can receive from the server.
AsyncBoolean type
Default value: true
.
Indicates whether the request is asynchronous. The synchronization request locks the browser until the remote data is acquired before other operations can be performed.
Beforesendfunction Type
Specifies the callback function that needs to be executed before the request is sent. The function also has two parameters: the first is the jqXHR
object, and the second is the current settings
object. This is an Ajax event, and if the function returns false
, this Ajax request will be canceled.
CacheBoolean type
Default value: true
(the dataType
default is when ' script ' or ' Jsonp ' false
).
Indicates whether URL requests are cached. If set to false
force the browser not to cache the current URL request. This parameter is valid only for head, get requests (the POST request itself is not cached).
CompleteFunction/array Type
Specifies the callback function that needs to be executed after the request completes , regardless of success or failure. The function also has two parameters: one is an jqXHR
object and one is a string representing the request status (' Success ', ' notmodified ', ' Error ', ' timeout ', ' abort ', or ' parsererror '). This is an Ajax event.
Starting with jquery 1.5, the property value can be multiple functions in the form of an array , and each function will be executed by a callback.
ContentsObject Type 1.5 new
An object paired with "{string: Regular expression}" to determine how jquery will parse the response, given its content type.
ContentTypeString Type
Default value: ' Application/x-www-form-urlencoded; Charset=utf-8 '.
Sends data to the server using the specified content encoding type. The XMLHttpRequest specification stipulates that CharSet is always UTF-8, and you cannot force the browser to change character encoding if you change it to another character set.
ContextObject Type
The context object that sets the Ajax-related callback function (that is, a pointer within a function this
).
ConvertersObject Type 1.5 new
Default value: {‘* text‘: window.String, ‘text html‘: true, ‘text json‘: jQuery.parseJSON, ‘text xml‘: jQuery.parseXML}
.
A data type converter. The value of each converter is a function that returns the value of the response after the conversion.
CrossdomainBoolean type 1.5 new
Default value: The same domain request as false
, cross-domain request is true
.
Indicates whether the request is a cross-domain. Set to True if you want to force cross-domain requests in the same domain, such as the Jsonp form. For example, this allows the server end multiplicity to be directed to another domain.
Dataany type
Data sent to the server, which is automatically converted to a string type. If it is a GET request, it will be appended to the URL.
Datafilterfunction Type
Specifies the callback function that handles the raw data for the response. The function also has two parameters: one is the string representing the original data of the response, and the other is the dataType
property string.
DataTypeString Type
Default: jquery Smart guess, guessing range (XML, JSON, script, or HTML)
Specifies the type of data returned. The value of this property can be:
- 'XML ': Returns an XML document that can be processed using jquery.
- 'HTML ': Returns the HTML string.
- 'script ': Returns the JavaScript code. Results are not automatically cached. Unless a parameter is set
cache
. Note: On remote requests (not in the same domain), all post requests are converted to get requests. (because the script tag of the DOM will be used to load)
- 'JSON ': Returns JSON data. The JSON data will be parsed using strict syntax (attribute names must be double-quoted, all strings must be in double quotes), and an error will be thrown if parsing fails. Starting with jquery 1.9, the response of the empty content is returned
null
or {}
.
- 'jsonp ': Jsonp format. When calling a function using JSONP form, such as "url?callback=?", jquery automatically replaces the second one? The correct function name to execute the callback function.
- 'text ': Returns a plain text string.
ErrorFunction/array Type
Specifies the callback function to execute when the request fails . The function has 3 parameters: Jqxhr object, request status string (NULL, ' timeout ', ' Error ', ' Abort ' and ' ParserError '), error message string (the text description part of the response status, such as ' not Found ' or ' Internal Server Error '). This is an Ajax event. Cross-domain Scripting and cross-domain JSONP requests do not call this function.
Starting with jquery 1.5, the property value can be multiple functions in the form of an array , and each function will be executed by a callback.
GlobalBoolean type
Default value: true
.
Indicates whether global AJAX events are triggered. Setting this value to false
prevent global event handlers from being triggered, such as Ajaxstart () and Ajaxstop (). It can be used to control various AJAX events.
HeadersObject Type 1.5 new
Default value: {}
.
Specifies the additional request header information as an object. The request header X-Requested-With: XMLHttpRequest
will always be added, and of course you can also modify the default XMLHttpRequest value here. headers
the value in the Beforesend can override the beforeSend
request header set in the callback function (meaning that it is called first).
$.Ajax({
wr.: "My.php" ,
Headers: {
"Referer": "http://www.365mini.com" //some browsers do not allow the request header to be modified
, "user-agent" : "newLine" //some browsers do not allow the request header to be modified
, "x-power" : "newLine"
, "accept-language" : span class= "str" > "en-us"
}
ifmodifiedBoolean type
Default value: false
.
Allows the current request to fetch new data only when the server data changes (such as unchanged, the browser obtains data from the cache). It uses HTTP header information Last-Modified
to determine. Starting with jquery 1.4, he will also check the server's specified ' ETag ' to determine if the data has been modified.
isLocalBoolean type 1.5.1 new
Default value: Depends on the current location protocol.
Allows the current environment to be considered "local", such as a file system, even though jquery does not recognize it by default. Currently, the following agreements will be considered as Local: file
, *-extension
and widget
.
JsonpString Type
Overrides the name of the callback function for the JSONP request. This value is used instead of "url?callback=?" The "Callback" section in the.
Jsonpcallbackstring/function Type
Specifies a callback function name for the JSONP request. This value will be used instead of the random function name generated by jquery automatically.
Starting with jquery 1.5, you can also specify a function to return the desired function name.
MimeTypeString Type 1.5.1 new
A MIME type used to overwrite the MIME type of XHR.
PasswordString Type
The password used to respond to HTTP access authentication requests.
ProcessDataBoolean type
Default value: true
.
By default, data
data is passed through the property, and if it is an object (technically, as long as it is not a string), it will be processed 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
.
ScriptcharsetString Type
Sets the character set of the script file that the request loads. Only if the request is datatype as "JSONP" or "script", and type is "GET" is used to force the modification of CharSet. This corresponds to the CharSet property of the settings <script> tag. It is usually used only when the content encoding of the current page and remote data is different.
StatusCodeObject Type 1.5 new
Default value: {}
.
A set of numeric HTTP codes and functions that make up the object, when the corresponding code is called when responding. For example:
$.Ajax({
Url:A_not_found_url,
Executes the corresponding callback function when responding to the corresponding status code
StatusCode: {
50U: function () {
Alert ( "page Not found"
},
200: function () {
Alert ( "request Succeeded" Span class= "pun");
}
}
});
SuccessFunction/array Type
Specifies the callback function to execute after the request succeeds. The function has 3 parameters: The data returned by the request, the response status string, the jqXHR
object.
Starting with jquery 1.5, the property value can be multiple functions in the form of an array , and each function will be executed by a callback.
TimeoutNumber type
Sets the millisecond value for the request time-out.
TraditionalBoolean type
If you want to use the traditional way to serialize the parameter, set the property to true
.
typeString Type
Default value: "GET".
The request type can be either ' POST ' or ' GET '. Note : You can also use other request types such as ' PUT ', ' DELETE ' here, but they are not supported by all browsers.
URLString Type
Default value: The current page URL.
The destination URL of the request.
usernameString Type
The user name used to respond to HTTP access authentication requests.
XHRfunction Type
Default value: Under IE is ActiveXObject
(if available), in other browsers XMLHttpRequest
.
A callback function that is used to create and return a XMLHttpRequest object. You can override this property to provide your own XHR implementation, or to enhance its functionality.
XhrfieldsObject Type 1.5.1 new
An object with multiple field name-field value pairs that is used to set the local XHR object. A pair of "filename-file Values" is set in the native Xhr object. For example, if you want, you can use it to set the Xhr object's properties for cross-domain requests withCredentials
true
.
$. ({
url: A_cross_ Domain_url,
// Set the withcredentials of the Xhr object to True
xhrfields: Span class= "pun" >{
Withcredentials: Span class= "KWD" >true
}
Attention:
1. If you need to set some parameters in all your AJAX requests settings
, you can use the Jquery.ajaxsetup () function to set the global settings without having to set them separately each time you execute jQuery.ajax()
.
2. Before jquery 1.4 (inclusive), the complete
3rd parameter of the callback function for the option parameter, and so on, succes
error
is not a jquery encapsulated Jqxhr object, but a native XMLHttpRequest object.
return value
jQuery.ajax()
The return value of the function is the JQXHR type, which returns the Jqxhr object of the current request (JQuery 1.4 and previous versions return the native XMLHttpRequest object).
Example & Description
If no parameters are given jQuery.ajax()
, the current page is requested by default and the returned data is not processed.
jQuery.ajax()
Functions settings
, the commonly used properties are: URL, type, async, data, DataType, success, error, complete, beforesend, timeout, and so on.
Please refer to the following initial HTML code:
<divid="Content"></div>
The following is the jQuery.ajax()
jquery sample code associated with the function to demonstrate jQuery.ajax()
the specific use of the function:
$.ajax ({URL:"Jquery_ajax.php", type:"POST", Data:"Name=codeplayer&age=18", Success:function(data, Textstatus, JQXHR) {//data is the returned //Textstatus may be "success", "notmodified", etc. //JQXHR is a jquery-encapsulated XMLHttpRequest ObjectAlert ("returned data" +data); }}); $.ajax ({URL:"Jquery_ajax.php?page=1&id=3", type:"POST"//jquery automatically converts object data to "name=codeplayer&age=18&uid=1&uid=2&uid=3", data: {name: "Codeplayer", Age:18, UID: [1, 2, 3] } //execute when request succeeds, Success:function(data, Textstatus, JQXHR) {alert ("Returned data" +data); } //execute when request fails, Error:function(JQXHR, Textstatus, errormsg) {//JQXHR is a jquery-encapsulated XMLHttpRequest Object //textstatus may be: null, "Timeout", "Error", "Abort", or "ParserError" //errormsg may be: "Not Found", "Internal Server Error", etc.Alert ("Request failed:" +errormsg); }});//extract the URL separately as the first parameter (JQuery 1.5+ is supported)$.ajax ("jquery_ajax.php?action=type&id=3", {dataType:"JSON"//return data in JSON format, Success:function(data, Textstatus, JQXHR) {//assume that the returned string data is {"name": "Codeplayer", age:20} //jquery has helped us to convert the JSON string to the corresponding JS object, which can be used directlyalert (data.name);//Codeplayer}}); $.ajax ({//notice there's a parameter callback=?URL: "Http://cross-domain/jquery_ajax.php?name=Jim&callback=?&age=21", Async:false //synchronization request, the browser will be locked after sending the request, only wait until the request completes (regardless of success or failure), the user can not operate, JS code will continue to execute, DataType: "Jsonp"//return data in JSON format, Success:function(data, Textstatus, JQXHR) {//assume that the returned string data is {"site_name": "Codeplayer", "Site_desc": "Focus on programming development technology sharing"} //jquery has helped us to convert the JSON string to the corresponding JS object, which can be used directlyalert (DATA.SITE_DESC);//focus on programming development technology sharing}}); $.ajax ({//loads the specified JS file into the current documentURL: "Http://code.jquery.com/jquery-1.8.3.min.js", DataType:"Script"});
Jquery.ajax () function explanation