简体   繁体   English

Javascript Json内循环

[英]Javascript Json inside loop

I am trying to execute a loop with a JSON query inside it. 我正在尝试在其中执行带有JSON查询的循环。 My code looks something like: 我的代码看起来像:

for (var i = 0; i < numitems; i++) {
   var currentitem = items[i];
   $.getJSON("http://localhost/items.php", {'itemname' : currentitem},
   function (json) {
      alert (json);
   });
}

But it seems like the for loop doesn't wait for the json query to finish and immediately goes on to the next one. 但似乎for循环不等待json查询完成并立即继续下一个。 Is it possible to implement a loop (doesn't have to be a for loop) that executes the current JSON query and proceeds to the next element in the array once a response has been received from json? 是否有可能实现一个循环(不必是for循环)执行当前的JSON查询并在从json收到响应后继续执行数组中的下一个元素?

Thank you! 谢谢!

function nextItem(i)
{
  if(i < numitems)
  {
    var currentitem = items[i];
    $.getJSON("http://localhost/items.php", {'itemname' : currentitem},
      function (json) {
        alert (json);
        nextItem(i + 1);
      });
  }
}

nextItem(0);

Put this in the same place you currently have your for loop (don't move the function out). 把它放在你目前拥有for循环的同一个地方(不要移动该功能)。

$.getJSON is an asynchronous call, meaning that it returns almost instantly but doesn't complete until some time later. $ .getJSON是一个异步调用,意味着它几乎立即返回但直到一段时间后才完成。 That's why you pass it a callback---the callback (ie the function you pass in line 4) is what's executed when the AJAX request actually completes. 这就是你传递回调的原因---回调(即你在第4行传递的函数)是AJAX请求实际完成时执行的。 The docs have some more details. 文档有更多细节。

You'll want to rethink your strategy here: if you want these requests to be executed one-at-a-time, each needs to be called from the callback of the one before. 您需要在此重新考虑您的策略:如果您希望一次一个地执行这些请求,则需要从之前的回调中调用每个请求。 Or you'll just have to deal with the asynchronous nature of the callbacks; 或者你只需​​要处理回调的异步性质; it can be extremely useful. 它非常有用。

getJSON is asynchronous. getJSON是异步的。 The loop will not wait for the JSON response. 循环不会等待JSON响应。

Your code should still work, however your alert()s will be delayed. 您的代码应该仍然有效,但是您的alert()会被延迟。

If you want it to wait for the response you will need to make the callback function iterate through your list (my example probably wont work) 如果你想让它等待响应,你需要让回调函数迭代你的列表(我的例子可能不会工作)

var items = [ "im", "not", "sure", "whats", "in", "here" ];

function bahJSON(index) {
   if (!index) index=0;
   var currentItem = items[index];
   $.getJSON("http://localhost/items.php", {"itemname": currentItem },
   function(json) { 
      alert(json);
      if (index<items.length) {
         bahJSON(index+1);
      }
   });
}
bahJSON();

The following executes a JSON response after the previous JSON response has been completed: 在完成上一个JSON响应之后 ,以下内容执行JSON响应:

function nextItem(i) {
var currentitem = items[i];
$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost/items.php",
        data: "{'itemname' : currentitem}",
        dataType: "json",
        complete: function() {
            if (i<numitems) {
                i++;
           nextItem(i);
        }

        },
        error: function(request, status, errorThrown) {
            alert(status);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM