【发布时间】: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