[英]What's wrong with my data, received through JQuery AJAX request?
I'm making an API call with this code: 我正在使用以下代码进行API调用:
$.ajax({
type: "GET",
url: "https://example/example.json",
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
alert(data.folder.item);
}
})
That returns nothing, except for an error in the console saying: 除了控制台中的错误说:
"Uncaught TypeError: Cannot read property 'item' of undefined"
“未捕获的TypeError:无法读取未定义的属性'item'”
The JSON data looks like this when I use the url in the browser: 当我在浏览器中使用url时,JSON数据如下所示:
{
"folder": {
"item": 123123,
"item 2": false,
"item 3": "content",
"item 4": [
{
"subitem": "content"
},
{
"subitem": "content2"
}
]
}
}
I was expecting "123123" in the alertbox, but nope. 我本来希望警报框中显示“ 123123”,但没有。 So what am I doing wrong?
那我在做什么错?
If its a JSON string you are getting it will need to be parsed. 如果获取的是JSON字符串,则需要对其进行解析。 Try this:
尝试这个:
$.ajax({
type: "GET",
url: "https://example/example.json",
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
var parsed = JSON.parse(data);
alert(parsed.folder.item);
}
});
Or to force jquery to parse it for you: 或强制jquery为您解析它:
$.ajax({
type: "GET",
url: "https://example/example.json",
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
alert(data.folder.item);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.