0

当我在循环中运行 Ajax 请求时,成功的 ajax 不显示返回的数据......这是代码:

url = ["../siteAdmin/statistics/queriesAjax.php", "../siteAdmin/statistics/geographyAjax.php"];
tabContainerId = ['tabs-2', 'tabs-3'];

for(var i=0, len=url.length; i < len; i++){
    console.log(tabContainerId[i]);
    jQuery("#"+tabContainerId[i]).html('<img src="../assets/images/loading.gif"/>');
    jQuery.ajax({
        type:"GET",
        url:url[i],
        data:{ from:from, to:to },
        success: function (msg) {
            jQuery("#"+tabContainerId[i]).html(msg);
        },
        error: function (msg) {
            showError("Error occurred.", tabContainerId[i]);
        }
    });
}

在 HTML 元素中,我只看到 loading.gif。显示浏览器控制台中 ajax 成功的 Console.log(msg)。但在 HTML 元素中 - 不是。如果我设置 var i = 0 或 var i = 1,则显示数据。我在哪里做错了?

4

1 回答 1

2

您在i成功回调中使用了该变量,但是在执行回调时,i几乎可以肯定已经发生了变化。

您必须强制 i 成为回调函数闭包的一部分。一种方法是将 for 循环的内容放入立即调用的函数表达式 (IIFE):

url = ["../siteAdmin/statistics/queriesAjax.php", "../siteAdmin/statistics/geographyAjax.php"];
tabContainerId = ['tabs-2', 'tabs-3'];

for(var i=0, len=url.length; i < len; i++) {
    (function(idx) {
        console.log(tabContainerId[idx]);
        jQuery("#"+tabContainerId[idx]).html('<img src="../assets/images/loading.gif"/>');
        jQuery.ajax({
            type:"GET",
            url:url[idx],
            data:{ from:from, to:to },
            success: function (msg) {
                jQuery("#"+tabContainerId[idx]).html(msg);
            },
            error: function (msg) {
                showError("Error occurred.", tabContainerId[idx]);
            }
        });
    })(i);
}

In effect, this "saves" the value of i so it is the same when your callback functions use it.

I haven't run this code through lint or an interpreter, so there may be syntax errors.

于 2012-10-30T20:28:41.307 回答