您好我想从Google天气中获取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;
它不起作用。感谢
答案 0 :(得分:3)
XMLHttpRequest
是异步的。你需要使用回调。如果您不想使用完整的库,我建议您使用Quirksmode's XHR wrapper:
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。
答案 1 :(得分:-1)
你不能通过javascript来做到这是一个跨域请求。你必须做这个服务器端。
在PHP中你使用CURL。
使用Javascript无法完成您要做的事情。
答案 2 :(得分:-1)
好的,这里是代码:
<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>
它不会返回任何错误,但警报返回未定义。