How to read all values in an array returned by a PHP file using AJAX?
I am using AJAX to fetch a multidimensional array, so a multidimensional array is returned to AJAX, how can I deal with the data with AJAX? I need to read all values in the multidimensional array. I use the following code t开发者_运维知识库o return the array to AJAX.
$resultset=array();
while($row=mysql_fetch_assoc($result))
{
$resultset[]=$row;
}
print_r($resultset);
How to read all values in an array returned by a PHP file using AJAX?
While it is possible to parse the output of print_r in JavaScript, it would be rather silly to do so when robust libraries for other data formats already exist for both languages.
Use JSON (links at the bottom of the page will take you to libraries for generating it in PHP and reading it in JavaScript).
Yes, you can use JSON (JavaScript Object Notation) to transfer data across multiple platforms. If your data looks like:
<?php
$a = array( );
$a[ "foo" ] = array( );
$a[ "bar" ] = array( );
$a[ "foo" ][ "foo-1" ] = 1;
$a[ "foo" ][ "foo-2" ] = 2;
$a[ "foo" ][ "foo-3" ] = 3;
$a[ "foo" ][ "foo-4" ] = array( "yada", "yada" );
$a[ "bar" ][ "bar-1" ] = 1;
$a[ "bar" ][ "bar-2" ] = 2;
$a[ "bar" ][ "bar-3" ] = 3;
$a[ "bar" ][ "bar-4" ] = array( "blah", "blah" );
?>
Then its json_encode( $a ) will return:
{"foo":{"foo-1":1,"foo-2":2,"foo-3":3,"foo-4":["yada","yada"]},"bar":{"bar-1":1,"bar-2":2,"bar-3":3,"bar-4":["blah","blah"]}}
You can use the JavaScript's eval function to convert this string into an object and the iterate it just like you would iterate a php array.
PHP
echo json_encode($resultset);
JS:
var array = json_decode(input);
json_decode in javascript is not supported by default, you might use a framework to implement this functionality. E.g: in prototype:
var array = input.evalJSON();
I would personally use JSON for that. E.g. in php instead of print_r use json_encode($resultset). And in javascript use some JSON-supporting lib (jquery/mootools will do) to decode JSON. That is it.
精彩评论