在调用百度天气预报前,我们得先去了解百度天气预报提供的api接口,然后再去申请百度ApiKey。当然,去申请百度api密钥的前提是需要有个百度帐号。
百度天气预报api地址:http://lbsyun.baidu.com/index.php?title=car/api/weather
申请百度api密钥地址:http://lbsyun.baidu.com/apiconsole/key
我们使用Jquery中的Ajax技术来实现百度天气预报的调用,从接口示例中我们了解到需要调用的数据在weather_data这个数组里,里面的四个对象就是我们今天要调用的数据。这里我们要获取的值分别是date、currentCity以及weather_data数组下的date、dayPictureUrl、temperature、weather、wind这五个值,然后把对应的值通过Ajax技术显示更新到页面去即可。
对象示意图:
要实现的效果示意图:
html代码:
<div class="wrap"> <h3>日期:<span class="times"></span>城市:<span class="nowCity"></span></h3> <ul class="list"> </ul> </div>
css代码:
*{padding: 0;margin: 0;} body{font:16px/1 "Microsoft yahei",arial;} ul,li{list-style: none;} .wrap{width:820px; background-image: linear-gradient(#0E68BC 0%,#3A86CC 50%, 80%,#72ADE0 100%);margin: 0 auto;color: #fff;border-radius: 5px;} .wrap h3{font-size: 15px; text-align: center;line-height: 30px;} .times{margin-right: 5px;} .wrap ul{overflow: hidden;width: 820px;} .wrap li{width: 205px;float: left;} .wrap li div{ width: 205px; height: 50px; border-right: 1px solid #fff; border-top: 1px solid #fff;line-height: 50px; text-align: center;} .list img{vertical-align: middle;}
js代码
$(function(){ var $times=$(".times"); var $nowCity=$(".nowCity"); var $list=$(".list"); var oCity="广州";//设置城市 $.ajax({ type:"GET",//默认是GET url:"http://api.map.baidu.com/telematics/v3/weather?location="+oCity+"&output=json&ak=ohA7QHfg0BBrpiY4kyuIAAsD", dataType:"jsonp", success:function(data){ $nowCity.html(data.results[0].currentCity);//给城市赋值 $times.html(data.date);//把对象里的date赋值给时间 var oWeather = data.results[0].weather_data; for (var i = 0; i < oWeather.length; i++) { oWeathers(oWeather[i]); }; }, error:function(jqXHR){ alert("信息错误"+jqXHR.status); } }) function oWeathers(weathers){ var oLi='<li>'+ '<div>'+weathers.date+'</div>'+ '<div><img src='+weathers.dayPictureUrl+'></div>'+ '<div>'+weathers.temperature+'</div>'+ '<div>'+weathers.weather+'</div>'+ '<div>'+weathers.wind+'</div>'+ '</li>' $list.append(oLi); } })
注意:这里是用Jquery写的别忘了引入文件,还有一点是本文章的ApiKey是我个人私有,请务用在商业用途。
通过上述代码实现了百度天气的调用了,如有问题或者写的不对的地方欢迎指出。