【问题标题】:How properly get JSON from remote server using native JavaScript?如何使用本机 JavaScript 从远程服务器正确获取 JSON?
【发布时间】:2015-04-03 14:47:54
【问题描述】:

我正在从远程服务器 (openweathermap.org) 获取 JSON。我的代码有什么问题?这里是服务器响应的示例enter link description here

var getWeatherJSON = function (city) {
    var httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); 
    var jsonText;
    httpRequest.onreadystatechange = function () {
        //====jsonText after getting respons equals null====
        jsonText = httpRequest.readyState == 4 && httpRequest.status == 200 ? httpRequest.responseText : null;
    }
    httpRequest.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + city, true);
    httpRequest.send();
    return jsonText;
}

【问题讨论】:

  • 你需要在 onreadystatechange() 中做你的事情,你不能使用异步返回远程 url 的数据。您还可以将 open() 的第三个参数设置为 false,但这很糟糕,然后您需要返回 httpRequest.responseText 而不是您的 var。顺便说一句,没有理由将 ActiveXObject("Microsoft.XMLHTTP") 用于需要 cors 的东西;它不会像这样为 fork 添加任何设备支持。
  • 请阅读下面我发布的解决方案。如果您无法理解,请要求澄清。谢谢!

标签: javascript ajax json api url


【解决方案1】:

您不能从 getWeatherJSON 函数或 onreadystatechange 函数返回 jsonText。您只能使用此数据并调用可以使用此数据的函数。 喜欢:

httpRequest.onreadystatechange = function () {
  //====jsonText after getting respons equals null====
  jsonText = httpRequest.readyState == 4 && httpRequest.status == 200 ? httpRequest.responseText : null;
  callbackFunction(jsonText);
}

【讨论】:

    【解决方案2】:

    你可以把“真”改成“假”。它的工作。

    httpRequest.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + city, false);

    如果你使用“true”,它是异步请求,你应该使用“回调函数”。

    【讨论】:

      猜你喜欢
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2016-06-12
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      相关资源
      最近更新 更多