我想显示这个网址http://api.open-notify.org/astros.json/的名字
这是我的代码,
var astrosAPI = "http://api.open-notify.org/astros.json/";
$.getJSON(astrosAPI, function (json) {
var name = json.results[0].formatted_name;
console.log('Name : ', name);
});
我想用我的h3
标签显示它。我是JSON和jQuery的新手。我一直在
index.html:631 Uncaught TypeError: Cannot read property '0' of undefined error
如果您能够联系到特定端点而不被CORS阻止,则它必须是数据的格式。
查看数据,您的数据中没有名为results
的属性。尝试调试该行以查看变量json
的正确格式。它可能是一个string
,您需要调用JSON.parse(json);
才能将其正确地格式化为对象。
你应该能够做到:
var astrosAPI = "http://api.open-notify.org/astros.json/";
$.getJSON(astrosAPI, function (json) {
var name = json.people[0].name;
console.log('Name : ', name);
});