我正在尝试连接到一个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"
}但是,当我运行代码时,会得到以下错误:
Uncaught : api.total_bandwidth未定义
这里怎么了?Http.responseText已经是一个对象了吗?我把API定义错了吗?
这是api的反应
{"total_bandwidth": {"GB": 110842.05, "TB": 108.24, "PB": 0.11}}发布于 2021-11-13 14:56:23
您正在紧张对象(响应),然后尝试从字符串中获取"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.stringify“实际上是一个错误。
我想你是想用JSON.parse而不是JSON.stringify..。-罗宾·齐格蒙德
我认为您的意思是JSON.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://stackoverflow.com/questions/69955297
复制相似问题