2017-10-11 489 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

相關問題