views:

86

answers:

2

I first write the 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:

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.

Thanks!

+1  A: 

PHP's associative arrays become objects (hashes) in 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 Bailey
A: 

@Peter already explained, that associative arrays are encoded as JSON objects in PHP.

So you could also change your PHP array to:

$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:

j.post("notifications.php", {}, function(data){...}, 'json');
Felix Kling
thanks for the tip!
Pete