开发者

Javascript Json inside loop

开发者 https://www.devze.com 2023-01-12 10:34 出处:网络
I am trying to execute a loop with a JSON query inside it. My code looks something like: for (var i = 0; i < numitems; i++) {

I am trying to execute a loop with a JSON query inside it. 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 开发者_C百科goes on to the next one. 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?

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).


$.getJSON is an asynchronous call, meaning that it returns almost instantly but doesn't complete until some time later. That's why you pass it a callback---the callback (i.e. the function you pass in line 4) is what's executed when the AJAX request actually completes. 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. The loop will not wait for the JSON response.

Your code should still work, however your alert()s will be delayed.

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:

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);
        }
    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号