[英]Access array-elements inside JSON-object
I have the following json-object returned via response 我有以下通过响应返回的json对象
the function 功能
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
}
});
}
My question is how the movies-array are accessed in javascript? 我的问题是如何在JavaScript中访问电影数组 ? I cannot access it via response - if I do i get "undefined" returned. 我无法通过响应访问它-如果返回,则返回“未定义”。
ie response.movies 即response.movies
undefined 未定义
or response.movies[0] 或response.movies [0]
uncaught typerror cannot read property [0] of undefined 未捕获的Typerror无法读取未定义的属性[0]
Try response['movies[]']
. 尝试response['movies[]']
。 Also, you could console log the response
object and inspect what is inside it 另外,您可以控制台记录response
对象并检查其中的内容
对象的属性似乎是"movies[]"
,而不是"movies"
,您可以使用方括号表示法获取其值
console.log(response["movies[]"][0])
in your back end you're returning with bad naming , so 在您的后端,您将以不好的命名返回,因此
to access that array you've to access it as below response.["movies[]"]
要访问该数组,您必须按以下response.["movies[]"]
对其进行访问response.["movies[]"]
see below sample : 参见以下示例:
response = { "movies[]": ["1","2","3"] }; console.log(response["movies[]"]);
movies is array, use $.each
or .forEach()
电影是数组,请使用$.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);
})
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.