2017-10-11 68 views
-1

我一直在使用下面的代码来获取我认为是来自openweathermap API的JSON字符串。为什么JSON.parse适用于Google开发人员工具,但不适用于我的js文件?

var request = new XMLHttpRequest(); 

request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?lat=12&lon=-50&APPID=myKey'); 

request.send(); 

var data = JSON.parse(request.responseText); 

,当我访问它的JSON字符串直接是这样的:

{"coord":{"lon":-50,"lat":12},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":301.461,"pressure":1025.84,"humidity":100,"temp_min":301.461,"temp_max":301.461,"sea_level":1025.82,"grnd_level":1025.84},"wind":{"speed":6.68,"deg":80.5004},"clouds":{"all":32},"dt":1507680994,"sys":{"message":0.0025,"sunrise":1507712963,"sunset":1507755824},"id":0,"name":"","cod":200} 

然而,当我使用JSON.parse(request.responseText),我得到一个语法错误 - 未捕获的SyntaxError:意外JSON输入 结束在JSON.parse()来

但是当我使用解析在Chrome开发者工具,它工作正常,我可以用自己的钥匙例如访问值JSON.parse(data)['coord']['lon']返回-50

+1

在解析之前是否记录了'request.responseText'来验证它被提取? – Optional

+1

这是**不是**你如何阅读** async **操作的响应 – Dummy

+0

可能的重复[如何从异步调用返回响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-an-asynchronous-call) – Xufox

回答

1

在尝试获取响应的内容之前,您需要等待异步响应。可以这样实现:

request.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    var data = JSON.parse(request.responseText); 
    } 
}; 
+0

谢谢。它现在完美 – SJC

相关问题