I used to develop a new function for Mozilla Developer Network. It needs to load a BASIC script file and a JSON request at the same time. Because jQuery is used, it means jQuery. getScript and jQuery. getJSON are used. I know that both are asynchronous and return a Deferred (Promise mode implementation in jQuery, see deffered object) object. Therefore, I want to know if I can request them in order in a callback, just like most JavaScript loaders (such as curljs ). I am lucky to use jQuery to process two requests with One callback.
JavaScript code of jQuery
As I mentioned earlier, I need to load a script and a JSON file, just like this:
$. 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 ". done "// Well, everything has been loaded, you can work });
When the resource file is loaded, the done or callback will be triggered and I will know that the request is complete. Different callback parameters are returned for each request. The preceding response parameters are as follows:
// [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 we want to load another traditional Ajax request, just like getting an HTML 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);});
The Dojo Toolkit has a similar function a long time ago, but I don't know that modern jQuery can do the same. Processing multiple requests in One callback is required in many cases. It can be seen that jQuery is also keeping pace with the times.
Original article: David Walsh. name