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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9074807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:34:49  来源:igfitidea点击:

how to convert json/array from ajax responseText in to javascript array?

javascriptajaxjson

提问by Arpi Patel

I have used ajax in the code which works perfectly and give me json or array which ever I want as an output. the code I have used is,

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

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

var test = xmlhttp.responseText;
alert(test);

This test variable gives me json/array.

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

I want to get the data which I received in the test variable in the JavaScript array.

我想获取我在 JavaScript 数组中的 test 变量中收到的数据。

The question is, how can I decode json data in javascript array? I have used the code as,

问题是,如何在 javascript 数组中解码 json 数据?我已经使用了代码,

var output = new Array();  
output = json_decode(xmlhttp.responseText);

but this code is not giving me any output.
How can I do this two things?

但这段代码没有给我任何输出。
我怎样才能做到这两件事?

采纳答案by Niranjan Singh

Try this:

尝试这个:

var arr = xmlhttp.responseText.Split(',');

If it does not solve your problem then in your php code, use simple json_encode(your array);and on javascript, use myData= eval("(" + xmlHttp.responseText + ")");.

如果它不能解决您的问题,那么在您的 php 代码中,使用 simplejson_encode(your array);并在 javascript 上使用myData= eval("(" + xmlHttp.responseText + ")");.

I suggest you to follow this approach:

我建议您遵循以下方法:

Encode the data you want to send by using a PHP binding for JSONat the server and decode the same using Javascript library for JSON. as:

在服务器上使用JSONPHP 绑定对要发送的数据进行编码,并使用JSON 的 Javascript 库对其进行解码。作为:

var myObject = eval('(' + myJSONtext + ')');

or

或者

var myObject = JSON.parse(myJSONtext, reviver);

Note: Include json2 javascript file to your solution..

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

Problem with storing values in Array from php to AJAX

在 Array 中存储值从 php 到 AJAX 的问题

回答by Sudhir Bastakoti

Most browsers support JSON.parse(). Its usage is simple:

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


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

For the browsers that don't you can implement it using json2.js.

对于不支持的浏览器,您可以使用json2.js来实现它。

回答by Jashwant

json is nothing but javascript object notation. You just need to parse it as suggested by Sudhir. You can also use jQuery.parseJSON for it.

json 只不过是 javascript 对象表示法。你只需要按照 Sudhir 的建议解析它。您也可以使用 jQuery.parseJSON。

And to do ajax, I strongly suggest you to use some library, preferably jQuery.

做ajax,我强烈建议你使用一些库,最好是jQuery。

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/