JQuery basics-advanced Ajax

Source: Internet
Author: User

Content outline: 1. Load requests 2. handle errors 3. Request global events 4. JSON and JSONP 5. It is not easy to send a document to the jqXHR object. Please indicate the source for reprinting! In the basics of Ajax, we learned the most basic asynchronous processing method. This article describes some global request events, cross-origin processing, and other issues of Ajax. I. Loading requests when Ajax sends requests asynchronously, the request time may be long if the network speed is slow. If the request exceeds a certain period of time, the user will no longer be bored and close the page. If you can give the user some prompts during the request, such as: "loading...", the same request time will make the user experience better. JQuery provides two global events:. ajaxStart () and. ajaxStop (). The two global events are activated when the user triggers Ajax and the request starts (other requests are not completed. ajaxStart () is activated when the request ends (all requests are completed. ajaxStop (). // Display and hide the request loading prompt $ ('. loading '). ajaxStart (function () {$ (this ). show ();}). ajaxStop (function () {$ (this ). hide () ;}); PS: The above code is no longer valid in jQuery1.8 or later versions. You need to introduce the jquery-migrate backward compatible file to run it. The new version must be bound to the document element. $ (Document ). ajaxStart (function () {$ ('. loading '). show ();}). ajaxStop (function () {$ ('. loading '). hide () ;}); // if the request time is too long, you can set the timeout value $. ajax ({timeout: 500}); // If an ajax does not want to trigger a global event, you can set global cancellation $. ajax ({global: false}); 2. error Handling Ajax asynchronous submission cannot be completed successfully in all cases, and submission fails due to code asynchronous file errors or network errors. In this case, we should report the error and remind the user to resubmit or notify the developer to fix it. In the previous high-level encapsulation, there was no callback error processing, such as $. get (), $. post (), and. load (). Therefore, early methods use the global. ajaxError () event Method to return error messages. After jQuery1.5, you can use the local. error () method through concatenation. For the $. ajax () method, you can not only use these two methods, but also use its own attribute method error: function (){}. // $. Ajax () prompts error copying code 1 using attribute method $. ajax ({2 3 type: 'post', 4 5 url: 'test1. php ', 6 7 data: $ ('form '). serialize (), 8 9 success: function (response, status, xhr) {10 11 errors ('{box'}.html (response); 12 13}, 14 15 error: function (xhr, errorText, errorStatus) {16 17 alert (xhr. status + ':' + xhr. statusText); 18 19} 20 21}); copy the code // $. post () uses concatenation. the error () method prompts an error. The concatenation method will be later. fail () Replace $. post ('test1. php '). error (funct Ion (xhr, status, info) {// The parameter is the same as the above alert (xhr. status + ':' + xhr. statusText); alert (status + ':' + info) ;}); // $. post () uses global. ajaxError () event method error $ (document ). ajaxError (function (event, xhr, settings, info) {// event is the event object alert (xhr. status + ':' + xhr. statusText); alert (settings + ':' + info) ;}); 3. request global events jQuery provides many global event methods for Ajax operations ,. ajaxStart (),. ajaxStop (),. ajaxError () and other event methods. They are all global events triggered during the request. In addition to these, there are also some other global events :. ajaxSuccess () corresponds to a local method :. success (), executed when the request is successful.. AjaxComplete () corresponds to a local method:. complete (). After the request is complete, register a callback function.. AjaxSend (), there is no corresponding local method, only the attribute beforeSend, the function to be bound before the request is sent. // $. Post () uses the local method. success () Copy code 1 $. post ('test. php ', $ ('form '). serialize (), function (response, status, xhr) {2 3 values ('{box'}.html (response); 4 5 }). success (function (response, status, xhr) {6 7 alert (response); 8 9}); copy code // $. post () uses the global event method. ajaxSuccess () $ (document ). ajaxSuccess (function (event, xhr, settings) {alert (xhr. responseText) ;}); PS: the global event method is triggered by all Ajax requests and can only be bound to the document. The local method is for a specific Ajax. Most of the parameters of some global event methods are objects. You can obtain the attributes or methods of these objects by traversing them. // Traverse the properties of the settings object $ (document ). ajaxSuccess (function (event, xhr, settings) {for (var I in settings) {alert (I) ;}}); // $. the local method for completing the post () request. complete () $. post ('test. php ', $ ('form '). serialize (), function (response, status, xhr) {alert ('success ');}). complete (function (xhr, status) {alert ('complete') ;}); // $. the Global Method for completing the post () request. ajaxComplete () $ (document ). ajaxComplete (function (event, xhr, settings) {alert ('complete '); }); // $. The global method before the post () request is sent. ajaxSend () $ (document ). ajaxSend (function (event, xhr, settings) {alert ('before sending the request') ;}); // $. the ajax () method (used in parameters of this method in ajax basics) can be directly set through attributes. Copy code 1 $. ajax ({2 3 type: 'post', 4 5 url: 'test. php ', 6 7 data: $ ('form '). serialize (), 8 9 success: function (response, status, xhr) {10 11 hours ('{box'}.html (response); 12 13}, 14 15 complete: function (xhr, status) {16 17 alert ('complete' + '-' + xhr. responseText + '-' + status); 18 19}, 20 21 beforeSend: function (xhr, settings) {22 23 alert ('before the request' + '-' + xhr. readyState + '-' + settings. ur L); 24 25} 26 27}); copy the code PS: After jQuery1.5, use. success (),. error () and. the complete () concatenation method can be used. done (),. fail () and. replace always. 4. If JSON and JSONP are in the same domain, the $. ajax () method can load the JSON file by setting the dataType attribute. In a non-same domain, JSONP can be used, but it is also conditional. // $. Ajax () Load JSON file copy code 1 $. ajax ({2 3 type: 'post', 4 5 url: 'test. json ', 6 7 dataType: 'json', 8 9 success: function (response, status, xhr) {10 11 alert (response [0]. url); 12 13} 14 15}); copy the code to use JSONP if you want to perform cross-origin file operations. JSONP (JSON with Padding) is an unofficial protocol that allows the server to integrate Script tags to return to the client, cross-origin access is implemented through javascript callback (this is only a simple implementation form of JSONP ). // Code 1 for cross-domain PHP File Replication <? Php 2 3 $ arr = array ('A' => 1, 'B' => 2, 'c' => 3, 'D' => 4, 'E' => 5); 4 5 $ result = json_encode ($ arr); 6 7 $ callback = $ _ GET ['callback']; 8 9 echo $ callback. "($ result)"; 10 11?> Copy the code // $. getJSON () method to obtain JSON $. getJSON ('HTTP: // www. li. cc/test. php? Callback =? ', Function (response) {console. log (response) ;}); // $. the ajax () method obtains the JSON copy code for cross-origin retrieval $. ajax ({2 3 url: 'http: // www. li. cc/test. php? Callback =? ', 4 5 dataType: 'jsonp', // set it to jsonp here, so the above line can not be "? Callback =? "Now! 6 7 success: function (response, status, xhr) {8 9 console. log (response); 10 11 alert (response. a); 12 13} 14 15}); copy Code 5. before jqXHR object, we used the local method :. success (),. complete () and. error (). These three local methods are not called by the XMLHttpRequest object, but are called by the objects returned by global methods such as $. ajax () (see the preceding example ). This object is a jqXHR object, which is a superset of the native object XHR. // Obtain the jqXHR object and view the attributes and Methods. var jqXHR =$. ajax ({type: 'post', url: 'test. php ', data: $ ('form '). serialize ()}); for (var I in jqXHR) {document. write (I + '<br/>');} PS: If the jqXHR object is used, we recommend that you use it. done (),. always () and. fail () instead. success (),. complete () and. error (). In future versions, the three methods may be removed. // After successful callback, copy code 1 var jqXHR =$. ajax ({2 3 type: 'post', 4 5 url: 'test. php ', 6 7 data: $ ('form '). serialize () 8 9}); 10 11 12 13 jqXHR. done (function (response) {14 15 minutes ('{box'{.html (response); 16 17}); copy the code using the jqXHR concatenation method ratio $. the attributes of ajax () have three advantages: 1. it can be joined to improve readability. 2. the same callback function can be executed multiple times. 3. specify the callback function for multiple operations; // call back the jqXHR function after multiple successful operations are executed at the same time. done (). done (); // multiple operations specify the callback function test1.php file: <? Php echo 'test1. php'?> Test2.php file: <? Php echo 'test2. php'?> Var jqXHR1 = $. ajax ('test1. php '); var jqXHR2 = $. ajax ('test2. php '); // use the when method to process multiple data records at the same time. You do not need to write each data file separately! $. When (jqXHR1, jqXHR2 ). done (function (r1, r2) {alert (r1 [0]); // you can print the result of r1 to see alert (r2 [0]);}); For my Lover, c! Thank you, MR. Lee!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.