如何将json/array从ajax responseText转换为javascript数组?

Arp*_*tel 19 javascript ajax json

我已经在代码中使用了ajax,它完美地运行并给了我想要作为输出的json或数组.我用的代码是,

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://map_ajax_control.php",false);
xmlhttp.send();

var test = xmlhttp.responseText;
alert(test);
Run Code Online (Sandbox Code Playgroud)

这个测试变量给了我json/array.

我想获取我在JavaScript数组中的测试变量中收到的数据.

问题是,我如何解码javascript数组中的json数据?我用过代码,

var output = new Array();  
output = json_decode(xmlhttp.responseText);
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有给我任何输出.
我该怎么做这两件事?

Sud*_*oti 23

大多数浏览器都支持JSON.parse().它的用法很简单:


obj = JSON.parse(xmlhttp.responseText);
alert(obj.length);

对于没有的浏览器,您可以使用json2.js实现它.


Nir*_*ngh 15

试试这个:

var arr = xmlhttp.responseText.Split(',');
Run Code Online (Sandbox Code Playgroud)

如果它没有解决你的问题,那么在你的PHP代码中,使用简单的json_encode(your array);和javascript,使用myData= eval("(" + xmlHttp.responseText + ")");.

我建议你遵循这个方法:

使用服务器上的JSON PHP绑定对要发送的数据进行编码,并使用Javascript库对JSON进行解码.如:

var myObject = eval('(' + myJSONtext + ')');
Run Code Online (Sandbox Code Playgroud)

要么

var myObject = JSON.parse(myJSONtext, reviver);
Run Code Online (Sandbox Code Playgroud)

注意:将json2 javascript文件包含在您的解决方案中..

将数据从php存储到AJAX的问题