Quantcast
Channel: jQuery – David Walsh Blog
Viewing all articles
Browse latest Browse all 33

jQuery: Multiple AJAX and JSON Requests, One Callback

$
0
0

Read the full article at: jQuery: Multiple AJAX and JSON Requests, One Callback

Treehouse
Wufoo

I’ve been working on a new feature for the Mozilla Developer Network which requires loading of a basic script file as well as a JSON stream.  Since we use jQuery, that means a jQuery.getScript and a jQuery.getJSON.  I know those both work asyncronously and return a Deferred, so I wondered if there was a way that I could load them in parallel with one callback, much the way JavaScript loaders like curljs do.  I was in luck!  Using jQuery.when, I can load both requests concurrently with one callback!

The jQuery JavaScript

As I mentioned, my use case was loading a script and a JSON resource, so how it works is:

$.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"
	
	// Yay, stuff loaded and now we can do something!

});

When the resources are done loading, the done or then callback fires and I know the requests are complete.  Each request type provides a different callback argument object, so the above would provide:

// [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 wanted to add a traditional AJAX XHR request to the mix, say a widget template, we could do that too:

$.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 had this type of functionality for a long time but I’m stoked that modern jQuery allows for the same.  Making multiple requests with one callback seems as relevant as any other task these days, so jQuery’s definitely moving with the times!


Viewing all articles
Browse latest Browse all 33

Trending Articles