循环遍历 json 数组 jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7771616/
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
loop through json array jquery
提问by dzm
I'm trying to loop through this to get the 'name' values. This is what I currently have, but it doesn't seem to be working, tried a few others from what was posted here but nothing seemed to work.
我正在尝试遍历它以获取“名称”值。这是我目前拥有的,但它似乎不起作用,从这里发布的内容中尝试了其他一些,但似乎没有任何效果。
$.get("/get_names", {campaign_id: $('select[name="id"]').val()},
function(data){
$.each(data, function(i, item) {
alert(item);
});
}
);
Json being returned:
返回 Json:
[
{
"name":"age"
},
{
"name":"asdf"
},
{
"name":"drivername"
},
{
"name":"drivers"
},
{
"name":"firstname"
},
{
"name":"gender"
},
{
"name":"lastname"
},
{
"name":"make"
},
{
"name":"model"
},
{
"name":"vehicles"
},
{
"name":"year"
}
]
I've tried using:
我试过使用:
item.name
item[i].name
Any suggestions?
有什么建议?
Thank you!
谢谢!
回答by Rob W
You have to parse the string as JSON (data[0] == "["
is an indication that data
is actually a string, not an object):
您必须将字符串解析为 JSON(data[0] == "["
表示data
实际上是字符串,而不是对象):
data = $.parseJSON(data);
$.each(data, function(i, item) {
alert(item);
});
回答by Kevin B
you could also change from the .get()
method to the .getJSON()
method, jQuery will then parse the string returned as data
to a javascript object and/or array that you can then reference like any other javascript object/array.
您也可以从.get()
方法更改为.getJSON()
方法,然后 jQuery 会将返回的字符串解析为data
javascript 对象和/或数组,然后您可以像任何其他 javascript 对象/数组一样引用它。
using your code above, if you changed .get
to .getJSON
, you should get an alert of [object Object]
for each element in the array. If you changed the alert to alert(item.name)
you will get the names.
使用上面的代码,如果您更改.get
为.getJSON
,您应该会收到[object Object]
数组中每个元素的警报。如果您将警报更改为alert(item.name)
您将获得名称。
回答by Royi Namir
I dont think youre returning json object from server. just a string.
我不认为你是从服务器返回 json 对象。只是一个字符串。
you need the dataType of the return object to be json
您需要返回对象的数据类型为 json