2015-07-10 249 views
0

我想知道是否有方法可以通過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?

+0

當您登錄xhr.response您能得到什麼? – ChadF

回答

1

您應該將字符串解析爲JSON對象。就像這樣:

var data = JSON.parse(xhr.response); 
console.log(data.coord); 
1

你缺少的響應處理

var xhr = new XMLHttpRequest(); 
 
// when the async call finishes, we need to check what happened 
 
xhr.onreadystatechange=function(){ 
 
    // if it finished without errors 
 
    if (xhr.readyState==4 && xhr.status==200){ 
 
    // we get the data 
 
    var data = JSON.parse(xhr.responseText); 
 
    // this should be your json 
 
    //console.log(data.response.coord); 
 
    document.getElementById('response').innerHTML = xhr.responseText; 
 
    } 
 
}; 
 

 
// NOTE! for demo purposes I'm using another api query that does not require an api key, change this to your api url 
 
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London,uk", false); 
 
xhr.send();
<div id="response"></div>

1

你的反應是JSON,所以你需要先解析它。使用JSON.parse(xhr.response)解析響應。

像這樣:

JSON.parse(xhr.response)["coord"]["lat"] 
JSON.parse(xhr.response)["coord"]["lon"]