Javascript不接受JSON数据作为变量



我正在尝试连接到API以在我的网站上显示一些数据。

我已经将Http定义为new XMLHttpRequest();,将url定义为API端点。

这是代码:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.stringify(Http.responseText)
document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}

然而,当我运行代码时,我会得到以下错误:

未捕获类型错误:api.total_bandwidth未定义

这里出了什么问题?Http.responseText是否已经是对象?我对API的定义有错吗?

这是api:的响应

{"total_bandwidth": {"GB": 110842.05, "TB": 108.24, "PB": 0.11}}

您正在字符串化对象(响应(,然后尝试获取"TB";来自字符串。

尝试解析api,然后从中获取属性:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.stringify(Http.responseText);
var apiJson = JSON.parse(api);
document.getElementById("stat").innerHTML = "Powering over " + apiJson.total_bandwidth.TB + "TB of private internet traffic";
};

编辑:原来"JSON.stringfy";实际上是个错误。

我想你是想用JSON.parse而不是JSON.stringfy…-Robin Zigmond

我想你指的是JSON.parse(对响应文本进行PARSE(,而不是JSON.stringify:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.parse(Http.responseText);
document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}

有关JSON.parse的更多信息,请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

最新更新