Iterate through Json Array

Edit This is a function in which I get a response from

$(document).ready(function()
{

  $.ajax({
    method: "get",
    url: 'ctr_seearmylist.php',
    dataType: 'jsonp',
    data: 'get=squad',
    success: processSquads
  });

});

and this is the php fragment that creates the response:

{..... //iterates throuh a result taken from the database
  $temp[0]=$id;
   $temp[1]=$squad_id;
   $result[]=$temp;
  }
  $result=json_encode($result);
  }
return $result;
}

if I call a warning (response.constructor); I get

function Array() {
    [native code]
}

Edit end

How to iterate through json array using jquery or javascript or does something work?

json response i get has the following form: [["1", "12"], ["2", "3"], ["3", "7"]]

I should mention that using response.length; has no effect

function processSquads(response)
{
  alert (response[0][0]); // works and returns 1 
  alert (response[0]); // works and returns 1,12
  alert (response.length); //doesn't work so I can't iterate 
}

Sorry for the many questions today, but I'm just starting out with Ajax and I'm stuck.

+3
source share
4 answers

Using jQuery:

var arr = [["1","12"],["2","3"],["3","7"]];
jQuery.each(arr, function() {
  alert(this[0] + " : " + this[1]);
});
//alerts: 1 : 12, etc.

Iterates an array and then shows what is at index 0 and 1.

+5

json,

: http://jsfiddle.net/w6HUV/2/

var array = [["1", "12"], ["2", "3"], ["3", "7"]];

processSquads(array);

function processSquads(response) {
    alert(response[0][0]); // 1
    alert(response[0]); // 1, 12
    alert(response.length); // 3

    $(array).each(function(i){
        alert(response[i]); // 1,12 - 2,3 - 3,7
    });
}
+1

, :

function processSquads(response)
{
  for(var list in response)
  {
    for(var item in response)
    {
      alert(item);
    }
  }
}
0

Not sure why jQuery answers are posted here, but you have to find out why the property lengthdoesn't work when needed. Posting jQuery code from one of the answers using JavaScript with hazelnuts.

var arr = [["1","12"],["2","3"],["3","7"]];
for(var i = 0; i < arr.length; i++) {
    var item = arr[i];
    console.log(item[0] + " : " + item[1]);
}

Can you post a reproducible example of what you are doing on jsfiddle or some other site?

0
source

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


All Articles