简体   繁体   English

jQuery的JSON响应-处理的正确方法是什么?

[英]JSON response with jQuery - what is the correct way to handle?

When using the $.ajax call in JQuery, what is the correct way to get the variables in this JSON feed: 在JQuery中使用$.ajax调用时,在此JSON feed中获取变量的正确方法是什么:

{"response": [ {"code":"2", "responseText":"No comments added."}]}

Typically, I use the $.each to loop through the various elements of the JSON response, but when there is only one item with sub items, I just figured it would be something like this: 通常,我使用$.each遍历JSON响应的各个元素,但是当只有一个带有子项目的项目时,我只是想像这样:

$.ajax({
        type: "GET",
        url: "http://localhost/comments.php",
        data: "userID=" + user_id + "&start=0",
        dataType: "json",
        success: function(data) {
        alert(data.response.code); //2
        }
});

However I am getting an undefined variable when I attempt this. 但是,当我尝试这样做时,我得到了一个未定义的变量。 This seems so easy, however I am really struggling. 这似乎很容易,但是我真的很努力。 Any tips or pointers? 有任何提示或指示吗?

Since the result is an array of objects, you need to first get the object from the array, and then access the properties of that object. 由于结果是对象数组,因此您需要首先从数组中获取对象,然后访问该对象的属性。

data.response[0].code

should work. 应该管用。

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

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