循环遍历json数组jquery
我正在尝试循环它以获取“名称”值。这是我目前所拥有的,但它似乎不起作用,尝试了此处发布的其他一些内容,但似乎没有任何效果。
$.get("/get_names", {campaign_id: $('select[name="id"]').val()},
function(data){
$.each(data, function(i, item) {
alert(item);
});
}
);
返回的 Json:
[
{
"name":"age"
},
{
"name":"asdf"
},
{
"name":"drivername"
},
{
"name":"drivers"
},
{
"name":"firstname"
},
{
"name":"gender"
},
{
"name":"lastname"
},
{
"name":"make"
},
{
"name":"model"
},
{
"name":"vehicles"
},
{
"name":"year"
}
]
我尝试过使用:
item.name
item[i].name
有什么建议吗?
谢谢你!
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:
[
{
"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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须将字符串解析为 JSON(
data[0] == "["
表示data
实际上是一个字符串,而不是一个对象):You have to parse the string as JSON (
data[0] == "["
is an indication thatdata
is actually a string, not an object):您还可以从
.get()
方法更改为.getJSON()
方法,然后 jQuery 会将返回的字符串解析为data
一个 javascript 对象和/或数组,您可以像任何其他 javascript 对象/数组一样引用它。使用上面的代码,如果您将
.get
更改为.getJSON
,您应该会收到[object Object]
中每个元素的警报大批。如果您将警报更改为alert(item.name)
,您将获得名称。you could also change from the
.get()
method to the.getJSON()
method, jQuery will then parse the string returned asdata
to a javascript object and/or array that you can then reference like any other javascript object/array.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 toalert(item.name)
you will get the names.我不认为你从服务器返回 json 对象。只是一个字符串。
您需要返回对象的 dataType 为 json
I dont think youre returning json object from server. just a string.
you need the dataType of the return object to be json