简体   繁体   English

遍历JSON响应失败

[英]Loop through JSON response fails

I get JSON response from a server: 我从服务器收到JSON响应:

[{"id":605,"vote":1},{"id":606,"vote":-1},{"id":611,"vote":1},{"id":609,"vote":-1}]

Then I try to loop through results and get objects properties: 然后,我尝试遍历结果并获取对象属性:

success: 
function (data) {
$.each(data, function() {
$.each(this, function(i, v) {
alert(i+v);
});    
});
}

But somehow my code fails and no alert is shown. 但是我的代码以某种方式失败,并且没有显示警报。 What am I doing wrong guys? 我在做错人吗?

Specify dataType to "json" in your ajax request: 在ajax请求中将dataType指定为"json"

 $.ajax({
     //...
     dataType:"json",
     success://etc...

Assuming there are no parsing issues with the string being in correct JSON format, you could do: 假设使用正确的JSON格式的字符串没有解析问题,则可以执行以下操作:

function (data) {
$.each(data, function() {
 console.log(this.id);
console.log(this.vote);
});
}

Try this: 尝试这个:

var data = [{"id":605,"vote":1},{"id":606,"vote":-1},{"id":611,"vote":1},{"id":609,"vote":-1}];
$.each(data, function( index, value ) {
  console.log( index + ": " + value.id + ", " + value.vote );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM