嘿伙计们我正在尝试向JSON页面发出请求,抓取数据,然后将其显示到我的控制台,但它正在给我" undefined"。那是为什么?
以下是代码,然后将在其下发布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"
}
答案 0 :(得分:2)
您的代码中有一些错误。
首先,它的一般结构应该是这样的
(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() {
//Code here
};
apodRequest.open("GET", url, true);
apodRequest.send(null);
}());
注意我是如何将apodRequest.open("GET", url, true);
和apodRequest.send(null);
移到onreadystatechange
处理程序之外的。
其次,而不是
apodRequest.onreadystatechange = function() {
if (apodRequest.readyState === 4 && apodRequest.status === 200) {
//Code here
}
}
你可以简单地做
apodRequest.onload = function() {
//Code here
};
因为它是在返回响应时将触发的事件。所以你不需要在里面进行if
检查。
最后,在onload
处理程序中,您有一些错误,例如:
data += parsedAPOD;
这是错误的,因为data
是undefined
到此为止,parsedAPOD
是一个对象。 +=
不会合并它们。如果要合并两个对象,还有其他方法,例如: Object.assign
击> for (i = 0; i < parsedAPOD.length; i++) { ... }
错误,因为parsedAPOD
是一个对象。对象没有length
属性,因此这不是迭代它的正确方法。请改用for ... in ...
循环data += parsedAPOD[i];
又错了,因为这不是合并对象的方式。parsedAPOD[i]
错误,因为i
是一个整数,在这种情况下,parsedAPOD[i]
只是未定义。希望此分析可以帮助您更正代码。
答案 1 :(得分:1)
首先parsedAPOD
是一个对象而parsedAPOD.length
无效。您可以使用for in
循环来迭代对象,如下所示。
for (var i in parsedAPOD) {
data += parsedAPOD[i];
console.log("Parsing lines: <br>" + parsedAPOD[i]);
}