【问题标题】:Looping incorrect in for each loop in jqueryjquery中每个循环的循环不正确
【发布时间】:2018-01-08 16:40:46
【问题描述】:

我将 na 元素推送到每个循环中的 javascript 数组中。但循环并不像预期的那样。

代码:

//lets say the length is 1 for array id.If its in error it has to loop 2 times, but looping only once
 $.each(id, function(i, itemI) {
         $.ajax({
                type: "GET",
                url: url1.trim(),
                dataType: "json",
                success: function(data) {//do something
                },
                error: function(xhr,status){
                  //push an element into array here
                  id.push("something");
                }
          });
       })

【问题讨论】:

  • “异步”
  • 什么不是预期的?你意识到 AJAX 调用是异步调用,所以 id.push 在循环结束之前永远不会发生?
  • 是的 - 我之前评论的含义是“不要这样做”。找到一种更好、更用户友好的方式来处理错误。
  • @StackAcc 摆脱循环并使用所有必需数据发出单个请求
  • 对我来说闻起来像是设计缺陷。为什么呼叫会因特定 ID 而失败?为什么发送不同的 ID 会导致它成功?为什么你不知道第一次发送什么?

标签: javascript jquery arrays


【解决方案1】:

根据doc$.each 最初采用对象/数组的length 属性并迭代直到满足length

你可以这样做。

var id=0, req = makeReq(id), makecalltimeout;
function makeReq(id)
{
    id = id || "something"; //If id is undefined during first call.
    var data = {id:id};
    $.ajax({
        type: "GET",
        url: "google.com",
        dataType: "json",
        data:data,
        success: function(data) {//do something
        },
        error: function(xhr,status){
           clearTimeout(makecalltimeout);
           makecalltimeout = setTimeout(makeReq(Math.floor(Math.random()*10)),1000)
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这里我会在它以 1 秒的时间间隔递归失败时发出请求。只是为了在参数中发送随机数据,我使用了Math.floor(Math.random()*10。你可以换成你喜欢的。

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 2018-04-25
    • 2019-07-21
    • 1970-01-01
    • 2015-11-23
    • 2017-02-08
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多