jQuery JSON 解码(PHP 到 Javascript)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17768105/
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
jQuery JSON Decode ( PHP to Javascript)
提问by Giulio Colleluori
I'm trying to make an autocomplete script. I pass variables through JSON, and then I don't know how to go on to decode JSON.
我正在尝试制作一个自动完成脚本。我通过JSON传递变量,然后我不知道如何继续解码JSON。
This is an example of the JSON code I got, and I'd like to convert it in a simple javascript array:
这是我得到的 JSON 代码示例,我想将其转换为一个简单的 javascript 数组:
[{"ID":"1","name":"Amateur astronomy \r"},{"ID":"2","name":"Amateur microscopy \r"},{"ID":"173","name":"Amateur radio \r"},{"ID":"299","name":"Amateur astronomy \r"},{"ID":"349","name":"Amateur theater \r"}]
回答by icktoofay
The standard JavaScript way to do this would be to use JSON.parse
:
执行此操作的标准 JavaScript 方法是使用JSON.parse
:
var myArray = JSON.parse(someJSONString);
For compatibility with older browsers that lack a built-in JSON
object, jQuery has its own method:
为了与缺少内置JSON
对象的旧浏览器兼容,jQuery 有自己的方法:
var myArray = jQuery.parseJSON(someJSONString);
Such method is deprecated as of jQuery/3.0.
这种方法从 jQuery/3.0 开始被弃用。
回答by Mark Hughes
The standard way with JavaScript is to use JSON.parse
:
JavaScript 的标准方法是使用JSON.parse
:
var myObject = JSON.parse( rawJSON );
If you're using jQuery with $.ajax
(or alternative) you can use dataType: 'json'
如果您将 jQuery 与$.ajax
(或替代) 一起使用,您可以使用dataType: 'json'
$.ajax({
type: 'GET',
url: 'request.php',
data: { variable: 'value' },
dataType: 'json',
success: function(data) {
// you can use data.blah, or if working with multiple rows
// of data, then you can use $.each()
}
});
Although, if your server sent back the header Content-Type: application/json
jQuery would return it like this anyway.
虽然,如果您的服务器发回标头,Content-Type: application/json
jQuery 无论如何都会像这样返回它。
Although the other way with jQuery is using $.parseJSON(rawJSON);
You don't have to do this if you're using the dataType.
尽管 jQuery 的另一种方式是使用$.parseJSON(rawJSON);
,但如果您使用的是 dataType,则不必这样做。
var JSONArray = $.parseJSON(rawJSON);