Preface
1.JSON and JSONP
2.jqXHR object one. 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
$.ajax ({
type: ' POST ',
URL: ' Test.json ',
dataType: ' JSON ',
success: function (response, status, XHR) {
alert (response[0].url);}
});
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
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).
The cross-domain PHP side file <?php
$arr = Array (' A ' =>1, ' B ' =>2, ' C ' =>3, ' d ' =>4, ' e ' =>5); $result = Json_encode ($arr );
$callback = $_get[' callback ');
echo $callback. " ($result) ";
? >
//$.getjson () method gets the JSON $.getjson (' http://www.li.cc/test.php?callback=? ', function (response) {
Console.log (response);
});
The $.ajax () method gets the JSON $.ajax across the domain ({
URL: ' http://www.li.cc/test.php?callback=? ', DataType: ' Jsonp ',
success: function (response, status, XHR) {
console.log (response);
alert (RESPONSE.A); }
});
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
two. JQXHR Objects
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 (). 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 () c4/>});
for (var i in jqxhr) {document.write (i + ' <br/> ');
}
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
Note: If you use the Jqxhr object, then the. Done (),. Always (), and. Fail () are recommended instead. Success (),. complete (), and. Error (). It is likely that these three methods will be scrapped in a future release.
After success, the callback function
Jqxhr.done (function (response) {
$ (' #box '). HTML (response);});
1 2 3 1 2 3
There are three major benefits to using JQXHR's concatenating approach than the property approach of $.ajax ():
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 the callback function
var jqxhr = $.ajax (' test.php '); var jqXHR2 = $.ajax (' test2.php ');
$.when (JQXHR, jqXHR2). Done (function (R1,R2) {alert (r1[0]);
Alert (r2[0]); });