简体   繁体   English

使用JavaScript(jQuery)解码JSON数组(从PHP)

[英]decoding an JSON array (from PHP) in Javascript (jQuery)

I first write the JSON: 我首先编写JSON:

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
print json_encode(array(
    "array" => $arr
));

Then in the jQuery I do: 然后在jQuery中,我这样做:

j.post("notifications.php", {}, function(data){

Now this is where I'm a little confused, as I would normally do: 现在这是我有点困惑的地方,就像我通常会做的那样:

data.array

To get the data, but I'm not sure how to handle the array. 要获取数据,但是我不确定如何处理数组。 data.array[1] didn't work. data.array[1]无效。

Thanks! 谢谢!

PHP's associative arrays become objects (hashes) in javascript. PHP的关联数组成为javascript中的对象(哈希)。

data.array.a === 1
data.array.b === 2
// etc

If you want to enumerate over these values 如果要枚举这些值

for ( var p in data.array )
{
  if ( data.array.hasOwnProperty( p ) )
  {
    alert( p + ' = ' + data.array[p] );
  }
}

@Peter already explained, that associative arrays are encoded as JSON objects in PHP. @Peter已经解释过,关联数组在PHP中被编码为JSON对象。

So you could also change your PHP array to: 因此,您也可以将PHP数组更改为:

$arr = array(1,2,3,4,5); // or array('a', 'b', 'c', 'd', 'e');

However, another important point is to make sure that jQuery recognizes the response from the server as JSON and not as text. 但是,另一个重要的一点是要确保jQuery将来自服务器的响应识别为JSON而不是文本。 For that, pass a fourth parameter to the post() function: 为此,将第四个参数传递给post()函数:

j.post("notifications.php", {}, function(data){...}, 'json');

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

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