Original article: jQuery: Multiple AJAX and JSON Requests, One Callback
Original Article Date: January 1, April 15, 2014
Translated on: February 1, April 22, 2014
Translated by: Tie
A common script file and a JSON stream to be loaded when I write code for Mozilla Developer Network (Mozilla Developer community. Because we use jQuery, this means we need to call jQuery. getScript and jQuery. getJSON functions. I know that all these functions are asynchronously executed (asyncronously) and will be returned after a delay of some time. So I wonder if there is a way for me to load them in parallel using a single callback, just like what curljs does. Lucky! With jQuery. when, I can concurrently Load two requests and only execute one callback!
JQuery script
As I mentioned, the following is an example of loading a script and a JSON Resource:
$. When ($. getScript ('/media/js/wiki-min.js? Build = 21eb633 '), $. getJSON ('https: // developer.mozilla.org/en-US/demos/feeds/json/featured /')). then (function (a, B) {// or you can also use ". done "// Yay, loading is complete. Here we can perform some dependency operations ...});
When the resource is loaded, the specified
DoneOr
ThenThe callback is triggered, so you can know that the request has been completed. The callback parameter object types returned by each request are different. Therefore, the preceding request may return the following information:
// Format: [response, state, jqxhr], [response, state, jqxhr] ["(function (c) {var e = c (". from-search-navigate "); if (e ...; If (j) {g. apply (m, l) }}) (window, document, jQuery); "," success ", Object] [Array [15]," success ", Object]
If you need to add a traditional ajax xhr request, such as a widget template, we can do this:
$.when($.getScript('/media/js/wiki-min.js?build=21eb633'), $.getJSON('https://developer.mozilla.org/en-US/demos/feeds/json/featured/'), $.get('/')).then(function(a, b, c) { console.log(a, b, c); });
Dojo Toolkit has such a feature for a long time, but jQuery can do the same. For current development, it is natural to share the same callback with multiple requests that are not synchronized and return in an unordered order. Therefore, jQuery is definitely keeping pace with the times!