jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jQuery.when理解大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用jQuery.when来触发两个ajax请求,然后在两个请求完成后调用一些函数。这里是我的@L_616_2@:
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',success: function(data) {
            count = data.d.__count;
        }
    });
};

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

但是这不工作像预期。 Ajax在method1中调用返回在showData()中使用的数据,而method2中的Ajax调用将返回计数,该值将被赋值给var count并在showData()中使用。

但是当我启动上面的@L_616_2@,method1被调用,然后method2然后showData留下showData中的数据为’未定义’。我怎么可以通过$ .when实现这一点,据我所知,只有当两个函数返回$ .promise执行时才会得到。我想要两个ajax调用应该并行调用,以后的结果显示基于两个调用的结果。

解决方法

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

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

这是一个工作jsFiddle

大佬总结

以上是大佬教程为你收集整理的jQuery.when理解全部内容,希望文章能够帮你解决jQuery.when理解所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。