简体   繁体   English

迭代Json数组

[英]Iterate through Json array

Edit This is the function where I get the response from 编辑这是我从中获得响应的函数

$(document).ready(function()
{

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

});

and this is the php snippet that creates the response: 这是创建响应的php片段:

{..... //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 alert(response.constructor); 如果我调用alert(response.constructor); I get 我明白了

function Array() {
    [native code]
}

End Edit 结束编辑

How do I iterate through a json array using jquery or javascript, or whatever works? 如何使用jquery或javascript迭代json数组,或者其他什么工作?

the json response i get has this form: [["1","12"],["2","3"],["3","7"]] 我得到的json响应有这样的形式:[[“1”,“12”],[“2”,“3”],[“3”,“7”]]

I should mention that using response.length; 我应该提到使用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 large number of questions today, but I'm just getting started with Ajax and I get stuck. 对于今天的大量问题感到抱歉,但我刚开始使用Ajax而且我遇到了问题。

With Jquery: 使用Jquery:

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

This iterates the array and then shows what is in index 0 and 1. 这将迭代数组,然后显示索引0和1中的内容。

that's not a json array, it's an array of arrays 这不是一个json数组,它是一个数组数组

this should work fine: http://jsfiddle.net/w6HUV/2/ 这应该工作正常: 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
    });
}

Untested but this should work: 未经测试但这应该有效:

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

Not sure why jQuery answers are posted here, but you should find out why the length property is not working when it should. 不知道为什么jQuery答案会在这里发布,但是你应该找出为什么length属性不能正常工作。 Posting the jQuery code from one of the answers with hazelnut JavaScript. 使用榛子JavaScript发布其中一个答案的jQuery代码。

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 an reproducible example of what you're doing on jsfiddle or some other site? 你能发布一个可重复的例子,说明你在jsfiddle或其他网站上做了什么吗?

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

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