简体   繁体   English

将php关联数组返回到javascript数组

[英]return a php associative array to javascript array

I am trying to return a php associative array to javascript array through ajaxRequest.responseText 我正在尝试通过ajaxRequest.responseText将php关联数组返回到javascript数组

Here's what I do. 这是我的工作。

First in php, I do this: 首先在php中,我这样做:

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

If I echo $encoded, I get {"a":"apple,arrow","b":"boy,bank","c":"cat,camp"} 如果回显$ encoded,我将得到{“ a”:“ apple,arrow”,“ b”:“ boy,bank”,“ c”:“ cat,camp”}

Then in js script, 然后在js脚本中,

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

If I alert thisarray, I get {"a":"apple,arrow","b":"boy,bank","c":"cat,camp"} 如果我提醒此数组,则会得到{“ 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. 不用说,我无法从thisarray调用我的值,因为它尚未定义为数组。

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: 您需要解析JavaScript中的JSON字符串以获得一个对象,最好是使用浏览器的本机JSON对象(如果有):

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. 否则,如果您已经在使用jQuery,则可以使用JSON.orgjQuery.parseJSONJSON解析器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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