Javascript Json内循环

Aam*_*oor 3 javascript jquery json

我正在尝试在其中执行带有JSON查询的循环.我的代码看起来像:

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

但似乎for循环不等待json查询完成并立即继续下一个.是否有可能实现一个循环(不必是for循环)执行当前的JSON查询并在从json收到响应后继续执行数组中的下一个元素?

谢谢!

Mat*_*hen 6

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);
Run Code Online (Sandbox Code Playgroud)

把它放在你目前拥有for循环的同一个地方(不要移动该功能).