【发布时间】:2016-11-05 23:12:16
【问题描述】:
大家好,我正在尝试向 JSON 页面发出请求,获取数据,然后将其显示到我的控制台,但它给了我“未定义”。这是为什么呢?
这是代码,然后JSON页面将发布在它下面:
(function Apod() {
var api_key = 'NNKOjkoul8n1CH1NoUFo',
url = 'https://api.nasa.gov/planetary/apod' + "?api_key=" + api_key,
data;
var apodRequest = new XMLHttpRequest();
apodRequest.onreadystatechange = function() {
if (apodRequest.readyState === 4 && apodRequest.status === 200) {
var response = apodRequest.responseText;
var parsedAPOD = JSON.parse(response);
data += parsedAPOD;
for (i = 0; i < parsedAPOD.length; i++) {
data += parsedAPOD[i];
console.log("Parsing lines: <br>" + parsedAPOD[i]);
}
}
apodRequest.open("GET", url, true);
apodRequest.send(null);
}
}());
JSON 页面解析:
{
"date": "2016-11-05",
"explanation": "Shot in Ultra HD, this stunning video can take you on a tour of the International Space Station. A fisheye lens with sharp focus and extreme depth of field provides an immersive visual experience of life in the orbital outpost. In the 18 minute fly-through, your point of view will float serenely while you watch our fair planet go by 400 kilometers below the seven-windowed Cupola, and explore the interior of the station's habitable nodes and modules from an astronaut's perspective. The modular International Space Station is Earth's largest artificial satellite, about the size of a football field in overall length and width. Its total pressurized volume is approximately equal to that of a Boeing 747 aircraft.",
"media_type": "video",
"service_version": "v1",
"title": "ISS Fisheye Fly-Through",
"url": "https://www.youtube.com/embed/DhmdyQdu96M?rel=0"
}
【问题讨论】:
-
究竟是什么显示未定义?响应是一个对象,而不是一个数组,所以它没有长度。循环根本不应该运行。
-
parsedAPOD是一个数组吗?所以请改用for in。 -
@MamdouhFreelancer do not use
for...in -
由于您的缩进,很难判断,但
apodRequest.open(...)在onreadystatechange处理程序中,因此永远不会被执行 -
xhr 响应上方的@vlaz 是一个对象,而不是一个数组。
标签: javascript json ajax parsing httprequest