jquery Basics---Ajax Basics tutorial (II.)

Source: Internet
Author: User

jquery Basics---Ajax advanced

Content outline:

1. Load Request

2. error Handling

3. Request Global Events

4.JSON and JSONP

5.jqXHR Object

The publication is not easy, reproduced please indicate the source!

In the Ajax basics, we learned about the most basic asynchronous processing methods. This article will look at some of the global request events, cross-domain processing, and other issues with Ajax.

A Load Request

When Ajax asynchronously sends a request, it encounters a slow speed, and the request takes longer. When a request exceeds a certain time, the user becomes impatient and closes the page. If you can give users some hints during the request, such as "trying to load ...", then the same request time will make the user experience even better.

JQuery provides two global events ,. Ajaxstart () and. Ajaxstop (). Both global events, as long as the user triggers Ajax, is activated when the request starts (not completing other requests). Ajaxstart (), the request ends (all requests are ended). Ajaxstop ().

Request load prompt display and hide

$ ('. Loading '). Ajaxstart (function () {

$ (this). Show ();

}). Ajaxstop (function () {

$ (this). Hide ();

});

PS: The above code in jQuery1.8 and later versions no longer valid, need to introduce jquery-migrate backwards-compatible files to run. In the new version, you must bind 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

$.ajax ({

timeout:500

});

If an AJAX does not want to trigger global events , you can set global cancel

$.ajax ({

Global:false

});

Two Error handling

When Ajax commits asynchronously, it is not possible for all cases to be completed successfully, as well as because of code async file errors and network errors that cause the submission to fail. At this point, we should report the error, reminding the user to resubmit or prompt the developer to fix it.

In the previous high-level package There was no callback error handling , such as $.get (), $.post (), and. Load (). Therefore, the earlier method returns an error message through the Global. Ajaxerror () event method. After jQuery1.5, you can use the Local. Error () method through concatenating processing. For the $.ajax () method, you can not only use these two methods, but also your own property method Error:function () {}.

$.ajax () Using property method hint Error

$.ajax ({2  3     type: ' POST ', 4  5     URL: ' test1.php ', 6  7     Data: $ (' form '). Serialize (), 8      9     Success:function (response, status, XHR) {Ten         $ (' #box '). HTML (response);          error:function ( XHR, ErrorText, ErrorStatus) {         alert (xhr.status + ': ' + xhr.statustext);     20 21});

$.post () uses the concatenating. Error () method to prompt for an error, and the Concatenating method is replaced by a. FAIL ()

$.post (' test1.php '). Error (Function (xhr, status, info) {//parameter is the same as above

Alert (Xhr.status + ': ' +xhr.statustext);

Alert (status + ': ' + info);

});

$.post () Use Global. Ajaxerror () Event method hint error

$ (document). Ajaxerror (Function (event, XHR, settings, info) {//event is the event object

Alert (Xhr.status + ': ' +xhr.statustext);

Alert (settings+ ': ' + info);

});

Three Request Global Events

JQuery provides many global event methods for Ajax operations, such as the. Ajaxstart (),. Ajaxstop (),. Ajaxerror (), and other event methods. They all belong to global events that are triggered at the request , and in addition to these, there are other global events :

. ajaxsuccess (), corresponding to a local method:. Success (), executed when the request was completed successfully.

. Ajaxcomplete (), corresponding to a local method:. Complete (), registering a callback function after the request is completed.

. Ajaxsend (), there is no corresponding local method, only the property beforesend, the function to bind before the request is sent.

$.post () uses a local method. Success ()

1 $.post (' test.php ', $ (' form '). Serialize (), function (response, status, XHR) {2 3     $ (' #box '). HTML (response); 4 5     }). Success(function (response, status, XHR) {6 7     alert (response); 8 9});

$.post () uses the global event method. Ajaxsuccess ()

$ (document). Ajaxsuccess (Function (event, XHR, settings) {

alert (Xhr.responsetext);

});

PS: The global event method is that all Ajax requests are triggered and can only be bound to the document. While the local method is for an Ajax.

For some of the parameters of the global event methods, most of them are objects, which properties or methods can be called, which can be obtained through the traversal method.

// Traverse Settings properties of the object

$ (document). Ajaxsuccess (function (event, XHR, settings) {

  for (var i in Settings) {

alert (i);

}

});

//$.post () The local method that the request was completed. Complete ()

$.post (' test.php ', $ (' form '). Serialize (), function (response, status, XHR) {

Alert (' success ');

}).Complete (function (xhr,status) {

Alert (' Done ');

});

//$.post () the global method for the request to complete. Ajaxcomplete ()

$ (document). Ajaxcomplete (Function (event, XHR, settings) {

Alert (' Done ');

});

//$.post () the global method before the request is sent. Ajaxsend ()

$ (document). Ajaxsend (Function (event, XHR, settings) {

Alert (' before sending request ');

});

The $.ajax () method (which participates in the parameters of this method in the Ajax Foundation) can be set directly through the property.

1 $.ajax ({2  3     type: ' POST ', 4  5     URL: ' test.php ', 6  7 9          success:function (response, S Tatus, XHR) {Ten         $ (' #box '). HTML (response);     },14     complete:function (xhr, status) {+         al ert (' Finish ' + '-' + xhr.responsetext + '-' + status ')    ,     beforesend:function (XHR, settings) {22 2 3         alert (' Before ' request ' + '-' + xhr.readystate + '-' + Settings.url ');     26 27});

PS: After the jQuery1.5 version, use the. Success (),. Error (), and. Complete () concatenating methods, which can be replaced with. Done (),. Fail (), and. Always ().

Four. JSON and JSONP

If the $.ajax () method is in the same domain, the JSON file can be loaded as long as the DataType property is set. In the non-identical domain, JSONP can be used, but it is also conditional.

$.ajax () load JSON file under the same domain

$.ajax ({2  3     type: ' POST ', 4  5     URL: ' Test.json ', 6  7     dataType: ' JSON ', 8  9     Success:function (response, status, XHR) {Ten         alert (response[0].url);     }14 15});

If you want to manipulate files across domains, we must use JSONP. JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration of Script tags back to the client to achieve cross-domain access in the form of JavaScript callback (this is simply a JSONP implementation form).

Cross-domain PHP-side files

1 <?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) ";?>

$.getjson () method get JSON across domains

$.getjson (' http://www.li.cc/test.php?callback=? ', Function (response) {

Console.log (response);

});

$.ajax () method get JSON across domains

1 $.ajax ({2  3     URL: ' http://www.li.cc/test.php?callback=? ', 4  5     dataType: ' Jsonp ',//set here for Jsonp so The above line can not  "callback="! 6  7     success:function (response, status, XHR) {8  9         console.log (response );         alert (RESPONSE.A);     }14 15});

Five. JQXHR Object

Before, we used the local method:. Success (),. complete (), and. Error (). These three local methods are not called by XMLHttpRequest objects, but are called by the objects returned by global methods such as $.ajax () (see example above). This object is the Jqxhr object, which is a superset of the native object XHR.

Get Jqxhr object, view properties and methods

var jqxhr = $.ajax ({

Type: ' POST ',

URL: ' test.php ',

Data: $ (' form '). Serialize ()

});

for (var i in jqxhr) {

document.write (i + ' <br/> ');

}

PS: If you use the Jqxhr object, it is recommended to use. Done (),. Always (), and. Fail () instead. Success (),. complete (), and. Error (). It is likely that these three methods will be scrapped in a future release.

Post-Success callback function

1 var jqxhr = $.ajax ({2  3     type: ' POST ', 4  5     URL: ' test.php ', 6  7     Data: $ (' form '). Serialize () 8  9});  jqxhr.done(function (response) {     $ (' #box '). HTML (response); 16 17});

using JQXHR the concatenating way than $.ajax () There are three major benefits to the property approach:

1. Can be concatenating operation, readability greatly improved;

2. The same callback function can be executed multiple times;

3. Specify a callback function for multiple operations;

Execute multiple successful callback functions at the same time

Jqxhr.done (). done ();

Multiple operations Specify callback functions

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 handle multiple processes at the same time, without having to write each individually!

$.when (JqXHR1, jqXHR2). Done (function (R1,R2) {

Alert (r1[0]); You can print the R1 and see the results.

Alert (r2[0]);

});

Original http://www.cnblogs.com/ttcc/p/3802639.html

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.