简单XMLHttpRequest(谷歌天气)

Simple XMLHttpRequest (Google Weather)

本文关键字:谷歌 XMLHttpRequest 简单      更新时间:2023-09-26

你好,我想从谷歌天气获取xml

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp= new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;

它不起作用。感谢

XMLHttpRequest是异步的。您需要使用回调。如果你不想使用一个完整的库,我建议你使用Quirksmode的XHR包装器:

function callback(xhr)
{
    xmlDoc = xhr.responseXML;
    // further XML processing here
}
sendRequest('http://www.google.com/ig/api?weather=london&hl=en', callback);

如果你绝对坚持自己实现这一点:

// callback is the same as above
var xmlhttp;
if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
    if (xmlhttp.readyState != 4) return;
    if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
    callback(xmlhttp);
};
xmlhttp.send(null);

编辑

正如@remi评论的那样:

我认为您会遇到一个跨域访问异常:您不能向页面以外的其他域发出ajax请求。不

这(在大多数情况下)是正确的。您需要使用服务器端代理,或者Google提供的任何API,而不是常规的XHR。

您不能通过javascript来实现跨域请求。您必须在服务器端执行此操作。

在PHP中,您可以使用CURL。

您想要做的事情是用Javascript无法完成的。

好的,这是代码:

<html>
<body>
<script type="text/javascript">
var xmlhttp;
var xmlDoc;
function callback(xhr)
{
    xmlDoc = xhr.responseXML;
    // further XML processing here
}

if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
    if (xmlhttp.readyState != 4) return;
    if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
    callback(xmlhttp);
};
xmlhttp.send(null);

alert(xmlDoc);
</script>
</body>
</html>

它不会返回任何错误,但alert返回undefined。