解码Javascript(jQuery)中的JSON数组(从PHP)
问题描述:
我首先编写JSON:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
print json_encode(array(
"array" => $arr
));
然后在jQuery中执行:
Then in the jQuery I do:
j.post("notifications.php", {}, function(data){
现在,这是我有点困惑的地方,就像我通常会做的那样:
Now this is where I'm a little confused, as I would normally do:
data.array
要获取数据,但是我不确定如何处理数组. data.array[1]
无效.
To get the data, but I'm not sure how to handle the array. data.array[1]
didn't work.
谢谢!
答
PHP的关联数组成为javascript中的对象(哈希).
PHP's associative arrays become objects (hashes) in javascript.
data.array.a === 1
data.array.b === 2
// etc
如果要枚举这些值
for ( var p in data.array )
{
if ( data.array.hasOwnProperty( p ) )
{
alert( p + ' = ' + data.array[p] );
}
}