繁体   English   中英

循环遍历每个JSON响应返回“[Object Object]”

[英]loop through each JSON response returns “[Object Object]”

我有成功的AJAX功能

success: function(response){
    console.log(response);
    if(response.success){
        $.each(response.vote, function(index, value){
            alert(value);
        });
    }   
}

这是来自控制台的JSON响应(参见下图)

来自控制台的JSON响应

但它会从警报提示,任何想法,线索,帮助,建议和建议中抛出“[对象]”。

不要使用alert而是console.log 您将能够以这种方式查看所有对象并避免垃圾邮件。

此外,如果您需要查看深层对象,可以使用类似https://github.com/WebReflection/circular-json的内容 ,这样可以打印甚至引用自身的对象(循环引用无法打印大对象) 。

alert使用对象的toString方法,该方法将返回此[Object Object]的东西。 如果要很好地打印对象,可以使用JSON.stringify(yourObject)

在您当前的代码中, value是一个对象,但是,alert只能显示string ,因此它将使用.toString将您的value转换为字符串,然后该字符串变为"[Object Object]"

要将value显示为键值对,请使用JSON.stringify(value)使其再次成为json

success: function(response){
    console.log(response);
    if(response.success){
        $.each(response.vote, function(index, value){
            alert(JSON.stringify(value));
        });
    }   
}

如果您只想访问值的属性,请使用它们的键应该工作:

success: function(response){
    console.log(response);
    if(response.success){
        $.each(response.vote, function(index, value){
            // This will alert each items' `bundle` value.
            // It's enough in your case, but you may have to check if the target attribute you want to alert is also an object.
            alert(value.bundle);
        });
    }   
}

如果要提醒该值而不是使用alert(JSON.stringify(value))

暂无
暂无

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

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