Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the callback hook provided by $.ajax () in jQuery

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces what is the callback hook provided by $.ajax () in jQuery. It has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

Callback Function Queues (callback function)

Callbacks accepted by beforeSend, error, dataFilter, success, and complete are called at the appropriate time.

Starting with jQuery 1.5, fail, done, and always callback hooks (hooks) starting from jQuery 1.6 adopt first-in, first-out queue management. This means that you can assign multiple callbacks to each hook. See Deferred object methods, which is the $.ajax () callback hook (hooks) inside the implementation.

Here is the callback hook (hooks) provided by $.ajax (), as follows:

BeforeSend is called before sending the request, and it receives the jqXHR object and settings as parameter objects.

Error is called when a request goes wrong. If the request fails, register in their order. They accept jqXHR, the error type represented by the string, and the exception object, if any. Some built-in errors take strings such as "abort", "timeout", "No Transport" as exception objects.

DataFilter is called after the request is successful. Pass in the returned data and the value of the dataType parameter. And the new data (which may be processed) must be returned and passed to the success callback function.

Success is called when the request succeeds and the returned data is received. Pass in the returned data, as well as the string and jqXHR object containing the success code.

When the complete request completes, regardless of whether it fails or succeeds, they perform callbacks sequentially. They receive a jqXHR object and one containing a success or error code.

Data Types (data type)

The $.ajax () function relies on the information provided by the server to process the returned data. If the server reports that the returned data is XML, the returned results can be traversed using the normal XML method or the jQuery selector. If you see other types, such as HTML, the data is treated as text.

The dataType option also allows you to specify other different data processing methods. In addition to simple xml,dataType, you can also specify html, json, jsonp, script, or text.

Where the data returned by the text and xml types is not processed. Whether through the responseText or responseXML of the jqXHR object, this data is simply a success passed to the processor

Note: we must make sure that the MIME type reported by the web server matches the dataType of our choice. Match. For example, in the case of XML, the server side must declare text/xml or application/xml to get consistent results.

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

If specified as a json type, the acquired data is parsed as a JavaScript object and the constructed object is returned as a result. To achieve this, he first tried to use jQuery.parseJSON (). If the browser does not support it, use a Function to constructor. Malformed JSON data will throw a parsing error (see json.org for more information). JSON data is a kind of structured data that can be easily parsed through JavaScript. If the acquired data file is stored on a remote server (the domain name is different, that is, data is obtained across domains), you need to use the jsonp type instead.

The jsonp type creates a query string parameter callback=? after the requested URL. The server should prefix the JSON data with the callback function name in order to complete a valid JSONP request. If you want to specify the parameter name of 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. He requires some server-side code to detect and process query string parameters. For more information, please refer to the original post that describes its use in detail.

When data is retrieved from a remote server (which is the only possible use of script or jsonp data types), error callbacks and global events will never be triggered.

Note: if the script or jsonp type is specified, the tag is actually used instead of the XMLHttpRequest object when the data is received from the server. In this case, $.ajax () no longer returns a XMLHttpRequest object and does not pass event handlers, such as beforeSend.

Sending Data to the Server (send data to server)

By default, Ajax requests use the GET method. If you want to use the POST method, you can set the type parameter value. This option also affects how the content in the data option is sent to the server. POST data will be sent to the server using the UTF-8 character set, according to the W3C XMLHttpRequest standard.

The data option can contain either a query string, such as key1=value1&key2=value2, or a mapping, such as {key1: 'value1', key2:' value2'}. If the latter form is used, the data is converted to a query string with jQuery.param () before it is sent. This process can also be avoided by setting the processData option to false. This may not be appropriate if we want to send a XML object to the server. And in this case, we should also change the value of the contentType option to replace the default application/x-www-form-urlencoded with another appropriate MIME type.

Advanced Options (Advanced option)

The global option is used to block callback functions that respond to registration, such as .ajaxSend (), .ajaxError (), and similar methods. This is useful in some cases, such as when requests are sent very frequently and briefly, you can disable this in .ajaxSend (). For cross-domain scripting and JSONP requests, the global option is automatically set to false. For more information about these methods, see below.

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

Ajax requests are time-limited, so after error warnings are caught and processed, they can be used to improve the user experience. The request timeout parameter is usually left at its default value, or it is set globally through $.ajaxSetup (), and the timeout option is rarely reset for a specific request.

By default, requests are always sent, but it is possible for the browser to call data from his cache. To disable the use of cached results, you can set the cache parameter to false. If you want to determine that the data has not changed since the last request, you can set ifModified to true.

ScriptCharset allows you to set a specific character set for tag requests 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 first letter of "asynchronous", which means that all operations are parallel and the order in which they are completed is not coherent. The async parameter of $.ajax () is always set to true, which indicates that other code can still execute after the request starts. Setting this option to false is strongly discouraged, which means that all requests are no longer asynchronous, which can cause browsers to lock up.

The $.ajax () function returns the XMLHttpRequest object he created. Usually jQuery only processes 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 an underlying interface to observe and manipulate the request. For example, .abort () on the calling object can suspend the request before it completes.

Currently, there is a bug in Firefox. Although .getResponseHeader ('Content-Type') returns a non-empty string, .getAllResponseHeaders () returns an empty string. Using jQuery in Firefox does not support automatic decoding of JSON CORS responses.

A solution for rewriting jQuery.ajaxSettings.xhr is as follows

(function () {

Var _ super = jQuery.ajaxSettings.xhr

XhrCorsHeaders = ["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"]

JQuery.ajaxSettings.xhr = function () {

Var xhr = _ super ()

GetAllResponseHeaders = xhr.getAllResponseHeaders

Xhr.getAllResponseHeaders = function () {

Var allHeaders = ""

Try {

AllHeaders = getAllResponseHeaders.apply (xhr)

If (allHeaders) {

Return allHeaders

}

} catch (e) {

}

$.each (xhrCorsHeaders, function (I, headerName) {

If (xhr.getResponseHeader (headerName)) {

AllHeaders + = headerName + ":" + xhr.getResponseHeader (headerName) + "\ n"

}

})

Return allHeaders

}

Return xhr

}

) ()

Thank you for reading this article carefully. I hope the article "what is the callback hook provided by $.ajax () in jQuery" shared by the editor is helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report