简体   繁体   中英

return a php associative array to javascript array

I am trying to return a php associative array to javascript array through ajaxRequest.responseText

Here's what I do.

First in php, I do this:

$encoded = json_encode($thisarray);
echo $encoded; 

If I echo $encoded, I get {"a":"apple,arrow","b":"boy,bank","c":"cat,camp"}

Then in js script,

thisarray = new Array();
thisarray = ajaxRequest.responseText;

If I alert thisarray, I get {"a":"apple,arrow","b":"boy,bank","c":"cat,camp"}

That's wrong since alerting an array should give error. But in this case, when I alert thisarray, I get the full array!!

Needless to say, I can't call my value out of thisarray, since it is yet defined as an array.

Anyone can tell me what am I missing here?

You need to parse the JSON string in JavaScript to get an object, preferably with the native JSON object of your browser, if available:

var thisarray = JSON.parse(ajaxRequest.responseText);

Otherwise you can use the JSON parser from JSON.org or jQuery.parseJSON if you're already using jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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