在Javascript(jQuery)中解码JSON数组(来自PHP)

时间:2022-10-17 09:19:57

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!

2 个解决方案

#1


1  

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] );
  }
}

#2


0  

@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. For that, pass a fourth parameter to the post() function:

但是,另一个重点是确保jQuery将服务器的响应识别为JSON而不是文本。为此,将第四个参数传递给post()函数:

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

#1


1  

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] );
  }
}

#2


0  

@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. For that, pass a fourth parameter to the post() function:

但是,另一个重点是确保jQuery将服务器的响应识别为JSON而不是文本。为此,将第四个参数传递给post()函数:

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