简单XMLHttpRequest(谷歌天气)
Simple XMLHttpRequest (Google Weather)
你好,我想从谷歌天气获取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。
相关文章:
- 谷歌地图固定位置覆盖
- 不显示带有本地json文件数据的谷歌地图脚本
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 谷歌放置API:按国家或餐馆名称搜索餐馆
- 谷歌地图标记不会显示
- 无法在JS中显示谷歌地图
- 科尔多瓦页面类应用程序中的多个谷歌地图
- 使用谷歌应用程序脚本将服务器端数据表返回到客户端
- 需要帮助谷歌地图方向面板在FancyBox中显示
- 在谷歌地图上获取事件的x,y坐标
- 使用谷歌应用程序脚本从工作表中获取值并将其显示在文本框中
- 谷歌地图API v3不适用于移动浏览器或PhoneGap
- 模拟谷歌地图中的点击
- 谷歌文档表面引擎
- 如何知道哪个标记被谷歌地图点击了
- 谷歌地图JS API+JSON-多个标记没有显示
- 如何在谷歌字体加载时显示加载图像
- 缓存谷歌地图数据
- 谷歌图表-如何更改整个表的css属性
- 谷歌地图劫持了iphone's滚动(触摸事件)-如何恢复