如何使用JSON从外部URL加载数据?

问题描述 投票:0回答:2

我想显示这个网址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
javascript jquery json dom
2个回答
-1
投票

如果您能够联系到特定端点而不被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);
});

0
投票

你必须使用success()done()函数。

var url = "http://api.open-notify.org/astros.json/";
$.getJSON(url).success(function (json) {
  var name = json.people[0].name
  console.log('Name : ', name)
})
© www.soinside.com 2019 - 2024. All rights reserved.