javascript - 将thingspeak中的JSON显示为HTML
问题描述
这是2年前完成的,一直工作到今天
它曾经从 thingspeak 上的 JSON 获取数据并将其显示给我
我需要帮助来了解发生了什么以及如何解决它
<html>
<head>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://api.thingspeak.com/channels/527143/feeds.json?
api_key=I6AD9OVB2SXX03HC&results=1', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
var dia = date.getDate();
var mes = date.getMonth();
mes++;
var ano = date.getFullYear();
var hora = date.getHours();
var minuto = date.getMinutes();
document.getElementById("camb").innerHTML = "Câmbio Dólar: R$ " + data.feeds[0].field1 + " |
Atualizado em " + dia + "/" + mes + "/" + ano + " às " + hora + ":" + minuto;
} else {
// We reached our target server, but it returned an error
}
};
request.send();
</script>
</head>
<body>
<div width = "100%" id="camb" style="font-size:15px; text-align:left; color: white; margin-
left: -300px; background-color: red; border-left: 300px solid red; border-bottom: 5px solid red;
border-top: 300px solid red; overflow: hidden; margin-top: -300px; font-family: Brandon,
Grotesque, sans-serif;"></div>
</body>
</html>
解决方案
像这样运行它并查看您的控制台。看起来你可能已经通过美化器或其他东西运行了你的代码,它改变了换行符/破坏了你的代码。
你会发现你在使用 CORS 时遇到了问题。解决此问题的一个好方法是https://github.com/Rob--W/cors-anywhere/
<html>
<head>
<script>
var request = new XMLHttpRequest();
var urlHere = "https://api.thingspeak.com/channels/527143/feeds.json?";
urlHere = urlHere + "pi_key=I6AD9OVB2SXX03HC&results=1";
console.log(urlHere);
request.open('GET', urlHere, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
var dia = date.getDate();
var mes = date.getMonth();
mes++;
var ano = date.getFullYear();
var hora = date.getHours();
var minuto = date.getMinutes();
document.getElementById("camb").innerHTML = "Câmbio Dólar: R$ " + data.feeds[0].field1 + " | Atualizado em " + dia + "/" + mes + "/" + ano + " às " + hora + ":" + minuto;
} else {
// We reached our target server, but it returned an error
}
};
request.send();
</script>
</head>
<body>
<div width = "100%" id="camb" style="font-size:15px; text-align:left; color: white; margin-
left: -300px; background-color: red; border-left: 300px solid red; border-bottom: 5px solid red;
border-top: 300px solid red; overflow: hidden; margin-top: -300px; font-family: Brandon,
Grotesque, sans-serif;"></div>
</body>
</html>
推荐阅读
- php - 带参数的 Symfony 自定义助手
- javascript - 两个类之间的动画颜色
- spring-boot - 用于 Bigquery 的 HiKariCP
- c++ - 下面代码中原型设计的行为
- android - 如何以编程方式在 android 中实现 SmartReply,就像 LinkedIn、Gmail、Google Allo 一样
- javascript - 如何在 beforeShowDay 中突出显示对象
- vbscript - Microsoft VBScript 运行时错误“800a000d”类型不匹配:“LastID”
- r - 将文本文件输出分成两个向量
- excel - 单元格中的动态平均值 (Excel 2016)
- angular - 无法从数据库中获取学生并将其显示在角度前端没有可见错误