我的代码没有在控制台中播放对象属性,但是代码可以很好地显示对象。我无法访问此对象中的信息的是什么?
下面是我的代码:
// APOD
(function Apod() {
var api_key = 'NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo';
var url = 'https://api.nasa.gov/planetary/apod' + "?api_key=" + api_key;
var apodRequest = new XMLHttpRequest();
var apodDATA = "";
apodRequest.onreadystatechange = function() {
apodRequest.onload = function() {
var responseObject = apodRequest.response;
apodDATA = responseObject;
$("document").ready(function() {
$("#apodimage").attr("src", responseObject.hdurl);
});
console.log(responseObject.url);
};
}
apodRequest.open("GET", url, true);
apodRequest.send(null);
}());下面是JSON "object“,它在responseObject变量上显示得很好(属性给我带来了未定义):
{
"date": "2016-11-06",
"explanation": "A mere 20,000 light-years from the Sun lies NGC 3603, a resident of the nearby Carina spiral arm of our Milky Way Galaxy. NGC 3603 is well known to astronomers as one of the Milky Way's largest star-forming regions. The central open star cluster contains thousands of stars more massive than our Sun, stars that likely formed only one or two million years ago in a single burst of star formation. In fact, nearby NGC 3603 is thought to contain a convenient example of the massive star clusters that populate much more distant starburst galaxies. Surrounding the cluster are natal clouds of glowing interstellar gas and obscuring dust, sculpted by energetic stellar radiation and winds. Recorded by the Hubble Space Telescope, the image spans about 17 light-years. Follow APOD on: Facebook, Google Plus, Instagram, or Twitter",
"hdurl": "http://apod.nasa.gov/apod/image/1611/ngc3603_hubble_3885.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Starburst Cluster in NGC 3603",
"url": "http://apod.nasa.gov/apod/image/1611/ngc3603_hubble_960.jpg"
} 发布于 2016-11-06 14:34:17
你从服务器得到的可能只是一个字符串,而不是一个对象。
您可以解析JSON字符串并使用JSON.parse将其转换为object。
var obj = JSON.parse(responseObject);
console.log(obj.url);您可以使用typeof检查变量的类型。所以如果你打印console.log(typeof responseObject),你会得到"string"。如果它是一个对象,你会得到"object"。
此外,由于您已经在使用jQuery,因此可以考虑由jQuery本身处理ajax请求。那样会更优雅。请阅读文档here。
发布于 2016-11-06 14:35:52
使用JSON.parse将响应转换为json,因为您的请求返回string
注意:-不要在ajax响应中使用$("document").ready()
它对我来说很好用
(function Apod() {
var api_key = 'NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo';
var url = 'https://api.nasa.gov/planetary/apod' + "?api_key=" + api_key;
var apodRequest = new XMLHttpRequest();
var apodDATA = "";
apodRequest.onreadystatechange = function() {
apodRequest.onload = function() {
var responseObject = apodRequest.response;
apodDATA = responseObject;
$("#apodimage").attr("src", responseObject.hdurl);
var json = JSON.parse(responseObject);
console.log(json.url);
};
}
apodRequest.open("GET", url, true);
apodRequest.send(null);
}());https://stackoverflow.com/questions/40446624
复制相似问题