Javascript Json编码js中的数据循环
我有php返回给JS的数据,但我不知道如何循环它来访问信息。。。我有这个:Javascript Json编码js中的数据循环,javascript,Javascript,我有php返回给JS的数据,但我不知道如何循环它来访问信息。。。我有这个: result = call_data('get_chat.php'); console.log(result); for(var data in result){ alert(result[data]["id"]); //says undefined } 控制台日志显示: [{"eventtime":"0000-00-00 00:00:00","
result = call_data('get_chat.php');
console.log(result);
for(var data in result){
alert(result[data]["id"]); //says undefined
}
控制台日志显示:
[{"eventtime":"0000-00-00 00:00:00","message":"test2","bywho":"dave","id":"2"},
{"eventtime":"0000-00-00 00:00:00","message":"testttt","bywho":"dave","id":"1"}]
所以我想循环每个数据,但我怎么做我真的很困惑!!每次都会说未定义。看起来您的php代码返回了一个对象数组,因此您需要首先遍历该数组,然后访问
id
键,如下所示:
for (var i = 0; i < result.length; i++){
var obj = result[i];
console.log(obj.id); // this will be the id that you want
console.log(obj["id"]); // this will also be the id
}
for(变量i=0;i
您的php代码似乎返回了一个对象数组,因此您需要首先遍历该数组,然后访问id
键,如下所示:
for (var i = 0; i < result.length; i++){
var obj = result[i];
console.log(obj.id); // this will be the id that you want
console.log(obj["id"]); // this will also be the id
}
for(变量i=0;i
如果typeof result==“string”
,则仍需要解析响应,然后才能对其进行迭代:
result = JSON.parse(call_data('get_chat.php'));
然后,正如其他人所指出的,您应该使用一个简单的for
循环和数组
s:
for (var i = 0, l = result.length; i < l; i++) {
console.log(result[i]["id"]);
}
for(变量i=0,l=result.length;i
for..in
循环将迭代所有可枚举键,而不仅仅是索引。如果typeof result===“string”
,则仍需要解析响应才能对其进行迭代:
result = JSON.parse(call_data('get_chat.php'));
然后,正如其他人所指出的,您应该使用一个简单的for
循环和数组
s:
for (var i = 0, l = result.length; i < l; i++) {
console.log(result[i]["id"]);
}
for(变量i=0,l=result.length;i
for..in
循环将迭代所有可枚举键,而不仅仅是索引。什么是console.log(typeof result)
say?看这个问题@JonathanLonowski,它只是说“string”是什么console.log(结果的类型)代码>说?看这个问题@JonathanLonowski它只是说“string”结果。长度=166如何。。。(typeof)for result是“string”=/@Dave,这是因为正如Jonathon指出的,这是一个json字符串,因此对其调用length
将返回字符串中的字符数。将其传递给JSON.parse
first.result.length=166无论如何。。。(typeof)for result是“string”=/@Dave,这是因为正如Jonathon指出的,这是一个json字符串,因此对其调用length
将返回字符串中的字符数。先把它传给JSON.parse
。该死,我错过了JSON解析!忘了吧!好位置,先生!该死的,我错过了!忘了吧!好位置,先生!