首页 > 解决方案 > 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 请求的网站似乎没有改变,我只是完全糊涂了。

标签: javascriptjson

解决方案


正如您在开发人员工具中看到的那样 - 有些事情显然发生了变化:

在此处输入图像描述

关于不推荐使用的同步请求的警告只是警告 - 但我们可以用异步请求修复它......错误的请求......似乎可以通过添加到查询字符串的任何内容来修复......

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');
});


推荐阅读