【问题标题】:repeating last element in jquery and ajax在 jquery 和 ajax 中重复最后一个元素
【发布时间】:2017-07-30 20:21:15
【问题描述】:

我的 ajax 请求的“for”循环有问题。我知道这里有很多不是最佳实践的,所以请原谅我,我才刚刚开始=]

这是我的代码:

var ServersObject = $("tr td:nth-child(2)");
var ServerArray = $.makeArray(ServersObject);
console.log(CurrentServer + 'outside ajax');
for (var i = 0; i < ServerArray.length; i++) {
    var CurrentServer = ServerArray[i].outerText;

    $.ajax({
        type: 'GET',
        data: { 'Server': CurrentServer },
        url: 'http://localhost/check',
        success: function(data) {
            if (data == '200') {
                console.log(CurrentServer + 'inside ajax');
                $("td:contains('" + CurrentServer + "')").next().text("OK");
            } else {
                $("td:contains('" + CurrentServer + "')").next().text("Not OK");
            }
        }
    });
}

如您所见,我有两条“Console.log”消息和一组服务器。 “outside ajax”消息像它应该的那样一一显示所有服务器,但“inside ajax”消息只显示阵列中的最后一个服务器。 我做错了什么?

谢谢!

【问题讨论】:

  • 已提出4个答案。可以给点意见吗?

标签: javascript jquery html node.js ajax


【解决方案1】:

您需要使用闭包来修复回调中的值,因为 CurrentServer 在您遍历数组时会发生变化。有几种方法可以做到这一点。这是一个:

for (var i = 0; i < ServerArray.length; i++) {
    var CurrentServer = ServerArray[i].outerText;

    (function(cs) {
      $.ajax({
        type: 'GET',
        data: { 'Server': cs },
        url: 'http://localhost/check',
        success: function(data) {
            if (data == '200') {
                console.log(cs + 'inside ajax');
                $("td:contains('" + cs + "')").next().text("OK");
            } else {
                $("td:contains('" + cs + "')").next().text("Not OK");
            }
        }
      });
    })(CurrentServer);
}

这个想法是你传递给函数的值(对于像字符串这样的标量对象)不会在函数之外改变。因此,通过以这种方式将值传递给函数(闭包),您可以“修复”成功回调中代码引用的值。

【讨论】:

    【解决方案2】:

    使用这个。

    for (var i = 0; i < ServerArray.length; i++) {
        var CurrentServer = ServerArray[i].outerText;
    
        $.ajax({
            type: 'GET',
            data: { 'Server': CurrentServer },
            url: 'http://localhost/check',
            success: function (data) {
                var newServer = ServerArray[i].outerText;
                if (data == '200') {
                    console.log(newServer + 'inside ajax');
                    $("td:contains('" + newServer + "')").next().text("OK");
                } else {
                    $("td:contains('" + newServer + "')").next().text("Not OK");
                }
            }
        });
    }
    

    【讨论】:

      【解决方案3】:

      内部的 Ajax 只记录一次?听起来status只有一次是200。会不会是另一个 .ajax 的快速执行在成功之前会覆盖(因为没有更好的词)前一个?

      另外,在您提供的代码中,外部日志永远不会起作用(我猜它应该在循环内)

      【讨论】:

        猜你喜欢
        • 2011-08-31
        • 2017-04-08
        • 2015-01-16
        • 1970-01-01
        • 1970-01-01
        • 2018-02-22
        • 2021-03-14
        • 1970-01-01
        • 2016-12-07
        相关资源
        最近更新 更多