jQuery 如何打印jquery对象/数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10231864/
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
How to print jquery object/array
提问by Sadu
I get id and category name from mysql database.
我从 mysql 数据库中获取 id 和类别名称。
When I am alerting a result, I get:
当我提醒结果时,我得到:
[{"id":"197","category":"Damskie"},"id":"198","category":"M\u0119skie"}]
(Is this object?)
(这是对象吗?)
How can I print a result like this:
Damskie
M\u0119skie
M\u0119ski - has bad encoding. It should be M?skie. How can I change this?
如何打印这样的结果:
达姆斯基
M\u0119skie
M\u0119ski - 编码错误。应该是M?skie。我怎样才能改变这个?
回答by thecodeparadox
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
$.each(arrofobject, function(index, val) {
console.log(val.category);
});
回答by Selvakumar Arumugam
What you have from the server is a string like below:
您从服务器获得的是一个如下所示的字符串:
var data = '[{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}]';
Then you can use JSON.parse
function to change it to an object. Then you access the category like below:
然后您可以使用JSON.parse
函数将其更改为对象。然后您可以访问如下类别:
var dataObj = JSON.parse(data);
console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return M?skie
回答by Kevin B
Your result is currently in string format, you need to parse it as json.
您的结果目前是字符串格式,您需要将其解析为 json。
var obj = $.parseJSON(result);
alert(obj[0].category);
Additionally, if you set the dataType of the ajax call you are making to json
, you can skip the $.parseJSON()
step.
此外,如果您将 ajax 调用的 dataType 设置为json
,则可以跳过该$.parseJSON()
步骤。
回答by Parth Raval
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
var data = arrofobject.map(arrofobject => arrofobject);
console.log(data)
for more details please look at jQuery.map()
有关更多详细信息,请查看jQuery.map()