日期:2014-05-17 浏览次数:20897 次
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>IP_Weather</TITLE> <script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script> <SCRIPT type="text/javascript"> //用于在页面判断天气信息是否准备好 var weather={"onReady":false}; function IpWeather() { //AJAX获取XMLHttpRequest var xmlhttp=false; /* Create a new XMLHttpRequest object to talk to the Web server */ /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlhttp = false; } } @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { xmlhttp = new XMLHttpRequest(); } //通过maxmind提供的脚本根据IP通过geoip_city()获得所在城市名,然后利用Google的API获得天气信息 xmlhttp.open('GET', 'http://www.google.com/ig/api?weather='+geoip_city()+'&hl=zh-cn', true); xmlhttp.send(""); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { //拿到返回的XML格式的天气信息 var weatherXML = xmlhttp.responseXML; //解析数据 var now = weatherXML.getElementsByTagName("current_conditions")[0]; var now_t = now.getElementsByTagName('temp_c')[0].getAttribute('data'); var now_w = now.getElementsByTagName('wind_condition')[0].getAttribute('data'); var now_c = now.getElementsByTagName('condition')[0].getAttribute('data'); var now_h = now.getElementsByTagName('humidity')[0].getAttribute('data'); var today = weatherXML.getElementsByTagName("forecast_conditions")[0]; var t_max = today.getElementsByTagName('high')[0].getAttribute('data'); var t_min = today.getElementsByTagName('low')[0].getAttribute('data'); //数据封装到JSON中,并将onReady改为True weather={"t_now":now_t,"wind":now_w,"cloud":now_c,"humidity":now_h,"t_max":t_max,"t_min":t_min,"onReady":true}; } } } //调用 IpWeather(); </SCRIPT> </HEAD> <BODY> <div id='target'></div> </BODY> <script type="text/javascript"> function weatherInfo() { if(weather.onReady) { document.getElementById('target').innerHTML="天气状况:"+weather.cloud+" 当前温度:"+weather.t_now+"℃ 全天温度:"+weather.t_min+"--"+weather.t_max+"℃ "+weather.humidity+" "+weather.wind; } else { document.getElementById('target').innerHTML="数据读取中。。。"; setTimeout("weatherInfo()",100); } } weatherInfo(); </script> </HTML>
if (window.XMLHttpRequest) { //