I get the following back from an $.ajax({ POST.....
[{"total_votes":1,"options":[{"id":40,"vote_count":0,"users":[]},{"id":41,"vote_count":1,"users":[{"photo":"xxxxxxxxxxx.png","name":"XXXXX,"id":1}]},{"id":42,"vote_count":0,"users":[]}]}]
so I try to get total_votes with:
success: function(e) {
console.log(e['total_votes'])
}
also try to get
console.log( e['options'].length() )
console.log( e['options'][0]['id'] )
Suggestions on why I keep getting undefined? Also is there a better way to loop through options?
Thanks
Your root object is an array, so you would need to do something like e[0]['total_votes']
. Also the length of an array is not a function its a property so you would want to do e[0].options.length
or e[0]['options'].length
.
使用$ .each()循环遍历它们
根据您的示例JSON响应(它在数组中),它将是e .total_votes
。
在解除引用JSON对象之前,需要调用JSON.parse
Formatted ur Json this way, you can get the "total_votes" value like this
success: function(e) {
console.log(e[0].total_votes);
}
[
{
"total_votes": 1,
"options": [
{
"id": 40,
"vote_count": 0,
"users": []
},
{
"id": 41,
"vote_count": 1,
"users": [
{
"photo": "xxxxxxxxxxx.png",
"name": "XXXXX",
"id": 1
}
]
},
{
"id": 42,
"vote_count": 0,
"users": [
{}
]
}
]
}
]
check out here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.