jQuery.when understanding

懵懂的女人 提交于 2019-11-27 03:10:56
Guillaume86
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);​

Here's a working jsFiddle

The problem is that you're passing showData() to then(), not showData. You should pass a reference to a function to .then():

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

or

$.when(method1(), method2())
    .then(function () {
        showData();
    });

Edit

I've put together a working demo. Part of the problem (at least in the code fragment you posted) was that there was no callback function named $callback. Part of the problem was the $ in the callback name '$callback'.

So, remove the jsonp: '$callback' ajax option, so that jQuery defaults to a callback function named callback, and define a function with that name, and it all works.

I have little bit modified your code and made simpler to understand... i haven't test it please try it

var count = 0;
function countResponse(data) {
    count++;
    if(count==2)
    {
        // Do something after getting responce from both ajax request
    }
};

var method1 = function() {
    return $.ajax('localhost/MyDataService/DataMethod_ReturnsData', {
        dataType: "jsonp",
        jsonp: "$callback",
        success: function(data) {
            countResponse(data)
        }
    });
};

var method2 = function() {
    return $.ajax('localhost/MyDataService/DataMethod_ReturnsCount', {
        dataType: "jsonp",
        jsonp: "$callback",
        success: function(data) {
            countResponse(data)
        }
    });
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!