How do I parse a PHP associative array with JavaScript?
I want to returning from the server some database elements using
AJAX.
1. Will AJAX allow my to return to a PHP associative array?
2. If so, how do I retrieve the data,ie parse the array into
elements? Would it be any better to return an indexed array?
I normally pass these as a json string containing an object where
object.attribute = value
for example, in my php I can create the json text:
----8<----8<----8<----8<----
<?php
header("Content-Type: text; charset=utf-8");
$str = "{ 'title' : 'Mr' , 'firstnames' : 'john henry' , 'lastname' :
'smith' , 'height' : 180 , 'weight' : 110 }";
echo $str;
?>
----8<----8<----8<----8<----
Note that there is no blank line at the end of the file, and no "\n" is
used, just a single one line string.
Next, in javascript I can use an XmlHttpRequest(xhr) object to request
the php file from the server, which will get a text response back, and
in the xhr processing, eval the text response:
var thePerson = JSON.parse('(' + responseText + ')');
then, in javascript:
thePerson.title = 'Mr'
thePerson.firstnames = 'john henry'
thePerson.lastname = 'smith'
thePerson.height = 180 (cms I guess)
thePerson.weight = 110 (kgs I guess)
Note that JSON.parse may not exist in older browsers, so you can either
supply it, or use the dreaded eval instead. It also leaves out a lot of
the javascript surrounding the use of ajax and the xhr object.
Rgds
Denis McMahon