jQuery.when了解 [英] jQuery.when understanding

查看:77
本文介绍了jQuery.when了解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery.when触发两个ajax请求,然后在两个请求完成后调用某些函数.这是我的代码:

I am trying to use the jQuery.when to fire two ajax requests and then call some function after the two requests have completed. Here's my code:

var count = 0;
var dfr;

var showData = function(data) {
    dfr.resolve();
    alert(count);
   // Do something with my data data received
};

var method1 = function() {
    dfr = $.Deferred();

    return $.ajax('localhost/MyDataService/DataMethod_ReturnsData', {
        dataType: "jsonp",
        jsonp: "$callback",
        success: showData
    });
};

var method2 = function() {
    return $.ajax('localhost/MyDataService/DataMethod_ReturnsCount', {
        dataType: "jsonp",
        jsonp: "$callback",
        success: function(data) {
            count = data.d.__count;
        }
    });
};

$.when(method1(), method2())
    .then(showData());

但是,这没有按预期进行. method1中的Ajax调用将返回要在showData()中使用的数据,而method2中的Ajax调用将返回要分配给var count并随后在showData()中使用的计数.

However this is not working as expected. Ajax call in method1 will return data which is to be used in showData() and Ajax call in method2 will return count which is to be assigned to var count and later used in showData().

但是当我启动上面的代码时,先调用method1,然后调用method2,然后再调用showData,将showData中的数据保留为'undefined'.我怎么能通过$.when实现这一点,据我所知,只有执行两个返回$.promise的函数时,它才会进行.我希望两个ajax调用都应该并行调用,然后根据两个调用的结果显示以后的结果.

But when I fire the above code, method1 gets called and then method2 and then showData leaving the data in showData as 'undefined'. How can I achieve this via $.when which as far as I know proceeds only when both functions returning $.promise are executed. I want that both the ajax calls should be called in parallel and later results be displayed based on results from both calls.

推荐答案

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: 'ashishnjain'
        },
        dataType: 'jsonp'
    });
}

function method2() {
    return $.ajax("http://search.twitter.com/search.json", {
        data: {
            q: 'ashishnjain'
        },
        dataType: 'jsonp'
    });
}

$.when(method1(), method2()).then(showData);​

这是一个正常工作的 jsFiddle

这篇关于jQuery.when了解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆