javascript - Javascript 在 JSON 请求中获取“GET https://www.purpleair.com/json 400 (Bad Request)”
问题描述
我有一个基本的 Javascript Web 应用程序,它发送 JSON 请求并读取从请求返回的数据。一周前,这段代码运行良好,没有错误。今天查了一下,每次都失败。在此期间我没有编辑任何东西。这是我的代码的 JSON 请求部分。
function Get(yourUrl){
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET",yourUrl,false);
Httpreq.send(null);
return Httpreq.responseText;
}
var json_obj = JSON.parse(Get('https://www.purpleair.com/json'));
results = json_obj.results;
控制台上的完整读数是:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
GET https://www.purpleair.com/json 400 (Bad Request)
谁能帮我弄清楚这笔交易是什么?自从我上次运行它以来,我发送 JSON 请求的网站似乎没有改变,我只是完全糊涂了。
解决方案
正如您在开发人员工具中看到的那样 - 有些事情显然发生了变化:
关于不推荐使用的同步请求的警告只是警告 - 但我们可以用异步请求修复它......错误的请求......似乎可以通过添加到查询字符串的任何内容来修复......
function Get(yourUrl, yourHandler){
var Httpreq = new XMLHttpRequest();
Httpreq.open("GET",yourUrl,true); // true makes this request async
Httpreq.onload = function(e) {
var json_obj = JSON.parse(Httpreq.response);
var results = json_obj.results;
yourHandler(results);
};
Httpreq.send();
return Httpreq;
}
var req = Get('https://www.purpleair.com/json?anything', function(results){
// here you can place some code to do something with results
// example below: alert the number of the results
alert(results.length + ' result recieved');
});
推荐阅读
- symfony - 如何在 phpunit 功能测试中模拟自动连接到 symfony 控制器的服务?
- c# - 在区间 [1000,9999] 中查找素数的更好解决方案,其中第一个和第二个之和
- node.js - NodeJS 视频流动态转码
- python - 从子进程获取无缓冲的输出无法正常工作 Python
- php - 如何使用 xero API 设置跟踪类别选项?
- image - OpenCV VideoCapture读取图片序列耗时太长,每帧40ms左右
- android - 改造 Post 方法抛出错误
- python - 将 DataFrame(具有日期索引)绘制为条形图
- c - 为什么char数组中的linux 0x80中断程序4号函数(sys_write)不起作用?
- python - 在 Python 中查找变量有什么特殊顺序吗?