2017-07-30 207 views
0

我已经通过响应访问数组元素

enter image description here

功能

function getUserList() { 

$.ajax({ 
    url: "https://reqres.in/api/users", 
    type: "POST", 
    data: { 
     name: "paul rudd", 
     movies: ["I Love You Man", "Role Models"] 
    }, 
    success: function(response){ 

     console.log(response); // prints the object 


    } 
}); 

} 

我的问题是电影阵列如何返回以下JSON对象在JavaScript中访问?我无法通过响应访问它 - 如果我确实得到“未定义”,则返回。

即response.movi​​es

未定义

或response.movi​​es [0]

未捕获typerror不能读取属性[0]的未定义

回答

2

对象的属性似乎是"movies[]",不"movies",为此,你可以用括号符号得到的

console.log(response["movies[]"][0]) 
2

尝试response['movies[]']。此外,您可以控制台日志response对象,检查里面是什么它

+0

我得到在这两种情况下 – java

+0

答案编辑不确定的,检查出来 – mattias

+1

感谢..... +1 – java

2

在你不好的命名返回你的后端,所以

访问阵列您对访问如下response.["movies[]"]

参见下面的示例:

response = { "movies[]": ["1","2","3"] }; 
 

 
console.log(response["movies[]"]);

1

电影是数组,使用$.each.forEach()

$.ajax({ 
    url: "https://reqres.in/api/users", 
    type: "POST", 
    data: { 
    name: "paul rudd", 
    movies: ["I Love You Man", "Role Models"] 
    }, 
    success: function(response) { 
    $.each(response.movies, function(index, value){ 
     // prints the object 
     console.log(value); 
    }) 
    } 
});