gpt4 book ai didi

javascript - 页面未显示 JSON 对象属性

转载 作者:行者123 更新时间:2023-11-29 19:09:11 25 4
gpt4 key购买 nike

我的代码没有在控制台中播放对象属性,但是代码显示对象的效果很好。我无法访问此对象中的信息是什么?

这是我的代码:

//                 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);
}());

这是在 responseObject 变量上显示良好的 JSON“对象”(属性给我未定义):

{
"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"
}

最佳答案

你从服务器得到的可能只是一个字符串,而不是一个对象。

您可以解析 JSON 字符串并使用 JSON.parse 将其转换为对象.

var obj = JSON.parse(responseObject);
console.log(obj.url);

您可以使用 typeof 检查变量的类型.因此,如果您打印 console.log(typeof responseObject),您将获得 “string”。如果它是一个对象,您将得到 "object"

此外,由于您已经在使用 jQuery,请考虑通过 jQuery 本身执行 ajax 请求。它会更优雅。阅读文档 here .

关于javascript - 页面未显示 JSON 对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com