In ASP.NET MVC, by default, we call actions which return JsonResult in separate HTTP AJAX requests.
Is there an easy way to call actions in one HTTP AJAX request without changing too much existing code? Suppose these actions all return JsonResult.
In ASP.NET MVC, by default, we call actions which return JsonResult in separate HTTP AJAX requests.
Is there an easy way to call actions in one HTTP AJAX request without changing too much existing code? Suppose these actions all return JsonResult.
You can take a look at using jQuery.when, which allows to execute callback functions when all requests have completed.
$.when($.ajax("request1"), $.ajax("request2"), $.ajax("request3"))
.done(function(data1, data2, data3){
// Do something with the data
});
Or
$.when($.ajax("request1"), $.ajax("request2"), $.ajax("request3"))
.then(successCallback, errorHandler);
More example:
function showData(data1, data2) {
alert(data1[0].max_id);
alert(data2[0].max_id);
}
function method1() {
return $.ajax("http://search.twitter.com/search.json", {
data: {
q: 'baid_harsh'
},
dataType: 'jsonp'
});
}
function method2() {
return $.ajax("http://search.twitter.com/search.json", {
data: {
q: 'baid_harsh'
},
dataType: 'jsonp'
});
}
$.when(method1(), method2()).then(showData);
Here's a working jsFiddle
References: