开发者

How to get the ajax results for multiple deferred calls in jquery?

I am trying to get the jquery deferred work as shown in the code below.

<script type="text/javascript">
    var appUrls = {
                      GetDataUrl : '@Url.Action("GetData")'
                  };

   开发者_开发知识库 function GetData1(){
        return $.getJSON(appUrls.GetDataUrl, { Id: 1 });
    }

    function GetData2() {
        return $.getJSON(appUrls.GetDataUrl, { Id: 2 });
    }

    $(function(){
        $("#result").html("Getting Data1, Data2 .... ");

        $.when(GetData1(), GetData2())
         .then(function(result){
             //The 'result' only contains the data from first request.  
             console.log(result);
             $("#result").html("Completed GetData1, GetData2"); 
         });

    });

    </script>

After both calls are completed I would like to extract the Json data returned from both the calls. However, the 'result' object only contains the data returned by the first call (GetData1)? How can I get the result for both the calls in the 'then' callback method above.


Since you have two requests you'll get two arguments result1,result2:

<script type="text/javascript">
var appUrls = {
    GetDataUrl : '@Url.Action("GetData")'
};

function GetData1(){
    return $.getJSON(appUrls.GetDataUrl, { Id: 1 });
}

function GetData2() {
    return $.getJSON(appUrls.GetDataUrl, { Id: 2 });
}

$(function(){
    $("#result").html("Getting Data1, Data2 .... ");

    $.when(GetData1(), GetData2())
    .then(function(result1,result2){
        console.log(result1);
        console.log(result2);
        $("#result").html("Completed GetData1, GetData2"); 
    });

});

</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜