I have developed a new feature for the Mozilla Developer Network, which requires loading a JSON request at the same time as a basic script file. Because we're using jQuery, it means using jquery.getscript and Jquery.getjson. I know that both are asynchronous and return a deferred (promise pattern implementation in jquery, see: Deffered object), so I want to know if I can request them sequentially in a callback. Just like most JavaScript loaders (such as Curljs). I was fortunate to be able to use jquery to process two requests with a callback.
jquery's JavaScript code
As I mentioned just now, 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" //OK, everything is loaded and ready to work});
When the resource file is loaded, done or callback will be triggered, and I know it has been requested. Each request returns a different callback parameter, such as the return parameter above, like this:
[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 a traditional Ajax request again, 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);});
Dojo Toolkit has a similar function long ago, but I don't know that modern jquery can. Dealing with multiple requests in a single callback is a requirement for multiple occasions, and it can be seen that jquery is also advancing with the times.
Original Davidwalsh.name