首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

怎么自定义天气预报

2012-11-12 
如何自定义天气预报很多时候大家都会用到天气预报,这里就结合自己所作的功能,讲下如何获取网上的信息,自定

如何自定义天气预报


很多时候大家都会用到天气预报,这里就结合自己所作的功能,讲下如何获取网上的信息,自定义一个天气预报,主要讲解数据获取。

1、采用jquery框架

2、数据来原:中国天气网

参考文献:

http://m.weather.com.cn/data5/city.xml

http://blog.csdn.net/hello_haozi/article/details/7564223

http://www.yovisun.me/sina-wangyi-ip-addr-api.html

http://blog.csdn.net/wei_ge163/article/details/8148107


3、实现原理

a.通过天气网提供的连接,得到本地网络IP

b.通过IP获取的当前城市

c.通过城市对比天气网提供的ID对照表,拼接自己所在城市的城市代码

d.通过城市代码获取到城市天气数据

注意:本代码实现只到地级市

4.具体代码实现如下

function getWeather() {    //request get current ip    $.ajax({url: 'http://61.4.185.48:81/g/', dataType: "script", success: function(result){        var weatherUrl;    //Current city url        var provinceCode;    //Current province code        var cityCode;    //Current city code        var H_CITY = ["北京", "上海", "天津", "重庆"];        if (ip){            var new_ip = ip.replace("_", "").replace("_", "");            //according to current ip get current city detail info            $.ajax({url: ('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' + new_ip), dataType: "script", success: function(_result){                if (remote_ip_info.ret == '1'){                       //get current province code                    provinceCode = getWeatherCode("http://m.weather.com.cn/data5/city.xml", remote_ip_info.province, 2);                    //get current province code                    cityCode = getWeatherCode("http://m.weather.com.cn/data5/city" + provinceCode + ".xml", remote_ip_info.city, 4);                    //get current weather url                    weatherUrl = "http://m.weather.com.cn/data/101"  + cityCode + (H_CITY.indexOf(remote_ip_info.city)!=-1?"00":"01") + ".html";                    queryWeather(weatherUrl);                } else {                       $("#weatherContent").html("没有找到匹配的 IP 地址信息!");                }            }, error: error, timeout: "3000"});        } else {               $("#weatherContent").html("没有找到IP信息!");        }    }, error: error, timeout: "3000"});}//find weather infofunction queryWeather(url) {        $.ajax({        url: url,        data: null,        success: success,        error: error,        dataType: "json",        timeout: "3000"    });   }//get city weather codefunction getWeatherCode(url, address, length) {    var str = $.ajax({url: url, async: false}).responseText;    var index = str.indexOf(address);    if(str && index == -1) {        $("#weatherContent").html("没有对应城市信息!");    } else {        return str.substring(index - (length + 1), index - 1);    }}var success = function(response){    parseToday(response.weatherinfo);};var error = function(xhr, status) {    $("#weatherContent").html("Http 请求错误!");  };var parseToday = function(weatherInfo){     //信息显示}

5、是不是很简单,你可以做出好看的自定义天气样式,也可以精确到地级市下面的区县,可以仔细看city 的xml定义。

热点排行