I am messing around with some JavaScript MVC patterns, and one of the features I need is to be able to make several ajax request (in my case, for the view and the model) and have one final callback when the data comes back (in my case run the controller). So I came up with this nice utility function, build on the top of jQuery, that does that:
var ajaxMulti = function(requests, callback){
var sucessIndex = 1,
numberOfRequests = requests.length - 1,
data = {};
$.each(requests, function(i, d){
$.ajax({
type: d.type,
url: d.url,
dataType: d.dataType,
success: function (d2) {
data[d.url] = d2;
if (sucessIndex > numberOfRequests) {
callback(data);
}
else {
sucessIndex++;
}
}
});
});
};
//usage
ajaxMulti([
{
type: "Get",
url: "ax/Util/getView/message.list",
dataType: "html"
},
{
type: "Get",
url: "zpravy/listIncomming",
dataType: "json"
}
], function(d){
console.log(d);
});
I am using the url as key, and what's nice about this is that it allows for different data formats for each request, which is what I need for my JavaScript MVC code.