开始通过XMLHttpRequest调用API

时间:2014-01-23 19:32:55

标签: javascript xml api xml-parsing xmlhttprequest

我刚开始学习如何使用API​​,但我在理解如何使用它们方面遇到了一些麻烦。

由于一些在线文档,我能够编写以下代码,但我对如何添加它有一些疑问:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml", false); xhr.send(); 
console.log(xhr);

现在,当我在浏览器中运行此代码并打开控制台时,我会得到一个包含大量内容的下拉列表。首先,我如何让代码显示响应?我希望控制台只显示我运行代码时要显示的XML。其次,我如何解析XML?有没有办法从XML元素中获取值并将其分配给JavaScript变量?

谢谢!

3 个答案:

答案 0 :(得分:5)

您正在打印的是XMLHttpRequest对象本身,而您实际需要的是来自您所做请求的响应。要获得响应,请使用

xhr.responseXML;

哪个是document类型的对象。 (见MDN docs)。

要展示代码,您可以

console.log(xhr.responseXML);

但是要真正使用响应,您可能希望按照Josh的建议进行操作,并从API请求JSON格式的响应(而不是XML格式的响应)。

您可能也希望异步执行此操作(请参阅this)。该页面有一个更强大的例子。让它适应它以显示伦敦的温度:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", true);
xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
      var response = JSON.parse(xhr.responseText);
      console.log("Temperature(K): " + response.main.temp);
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.onerror = function (e) {
  console.error(xhr.statusText);
};
xhr.send(null);

异步意味着一旦收到响应就会执行xhr.onLoad函数。因此,所有代码都将按顺序执行,并且只有在收到响应时才会执行onLoad。

答案 1 :(得分:1)

该下拉菜单可能是您的浏览器以交互方式为您格式化响应对象。

xmlDoc=xhr.responseXML;会为您提供实际结果文字

另外:您可以请求JSON对象,以便更轻松地处理数据。

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", false); xhr.send(); 
var data= JSON.parse(xhr.responseText); //data is now a javascript object full of the API data

注意网址现在如何读取mode=json

答案 2 :(得分:1)

您可以将回复作为Document object

使用上面的代码,您可以引用xhr.responseXML并使用Document documentation了解如何获取所需的数据。

相关问题