我想知道是否有方法可以通過JavaScript從API接收信息。我目前正在嘗試使用來自www.openweathermap.org的API提供的信息,但我不確定我如何使用JS做到這一點。我目前試圖從API獲取信息javascript
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?
lat=38.892634199999996&lon=-77.0689154", false);
xhr.send();
console.log(xhr);
其響應,向我發送信息JS對象格式:
{ response: {"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,"main":"Clear",
"description":"sky is clear","icon":"01d"}],"base":"cmc stations","main":{
"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,"temp_max":304.15},
"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},"dt":1436565479,
"sys":{"type":1,"id":1325,"message":0.008,"country":"US","sunrise":1436521925,
"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200}\n',
responseText: '{"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,
"main":"Clear","description":"sky is clear","icon":"01d"}],"base":"cmc stations",
"main":{"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,
"temp_max":304.15},"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},
"dt":1436565479,"sys":{"type":1,"id":1325,"message":0.008,"country":"US",
"sunrise":1436521925,"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200} }
我試過的console.log(xhr.response.coord)和執行console.log(xhr.responseText.coord )作爲一個例子,兩者都是未定義的。我需要做其他事情來打印信息嗎?
我知道你可以使用$ .get(URL,function())通過JQUERY接收信息,但有沒有一種方法我可以做到這一點只是JS?
當您登錄xhr.response您能得到什麼? – ChadF