延迟的ajax请求数组永远不会进入when.apply()。done()

时间:2014-07-27 18:34:12

标签: javascript jquery ajax jquery-deferred

我有以下代码来处理几个ajax请求,并等待它们全部进行处理并将它们的结果组合起来when.apply

var requestsArray = [];

var url = "http://...";

console.log("url: " + url);

var req1 = $.ajax({
    type: "GET",
    url: url,
    dataType : "xml"
});

req1.done(function (resp1) {
    $(resp1).find('interest').each(function() {

        var interest_id = $(this).find('id').text();
        var interest_name = $(this).find('name').text();

        var request = $.ajax({
              type:"GET",
              URL: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
              dataType: "jsonp"
        });
        requestsArray.push(request);

    });

    $.when.apply(null, requestsArray).done(function () {
        console.log(arguments);
         // You can collect the responses in the same order from `arguments`
        var responses = arguments;
    });

});

为什么它永远不会进入$.when.apply,而且它不打印任何console.log(arguments);

1 个答案:

答案 0 :(得分:2)

$.ajax({
    type:"GET",
    URL: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + 
//  ^^^
         interest_name + "&redirects&prop=text",
    dataType: "jsonp"
});

你拼错了$.ajax parameter。它必须是url,而不是URL

如果没有给出url,它将获取当前页面,该页面不是jsonp格式,这将导致一个parseerror,填充不会调用done回调而是{{3}你没有通过。