2

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.

4

1 回答 1

3

您可以查看使用jQuery.when,它允许在所有请求完成时执行回调函数。

$.when($.ajax("request1"), $.ajax("request2"), $.ajax("request3"))
 .done(function(data1,  data2, data3){
         // Do something with the data
 });

或者

$.when($.ajax("request1"), $.ajax("request2"), $.ajax("request3"))
.then(successCallback, errorHandler);

更多示例:

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);​

这是一个工作的jsFiddle

参考:

  1. SO - 如何在 jQuery 中进行批量 ajax 请求?
  2. SO - jQuery.when 理解
于 2013-04-16T05:03:06.590 回答