从API javascript获取信息

时间:2015-07-10 22:47:51

标签: javascript api

我想知道是否有一种方法可以通过JavaScript从API接收信息。我目前正在尝试使用来自www.openweathermap.org的API中的信息,但我不确定如何使用JS来完成它。我目前试过

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吗?

3 个答案:

答案 0 :(得分:1)

您应该将字符串解析为JSON对象。像这样:

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

答案 1 :(得分: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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您的回复是JSON,因此您需要先解析它。

使用JSON.parse(xhr.response)来解析响应。

像这样:

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