Javascript Json inside a loop

I am trying to execute a loop with a JSON request inside it. My code looks something like this:

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 that the for loop does not wait for the json request to complete and immediately proceeds to the next. Is it possible to implement a loop (it doesn't have to be a for loop) that executes the current JSON request and moves on to the next element of the array after receiving a response from json?

Thank!

+3
source share
4 answers
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 where you have the for loop (don't disable the function).

+6
source

$. getJSON - , , , . - (.. , 4) - , , AJAX . .

: , , . ; .

0

getJSON . JSON.

- , () s .

, , ( , , )

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();
0
source

After the JSON response is executed, the previous JSON response is executed after :

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
source

Source: https://habr.com/ru/post/1761030/


All Articles