jquery 之天气查询小部件
用ajax从网络接口获取对应的数据,然后显示。
本demo没有做css美化,比较丑。
数据接口:"http://api.map.baidu.com/telematics/v3/weather?location="+city+"&output=json&ak=EGgzZ22dsboWQEcPQ6KDQLknQd3YkkkP"
中间的city为选择的城市名称!
级联省市县的获取代码没有贴出,可以前往我的 github 仓库获取:https://github.com/qiuqiu2945/jquery/tree/master/questforWeather
这个代码使用了template模板来创建元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>获取天气</title>
<script src="./js/jquery-3.4.1.min.js"></script>
<script src="./js/template-web.js"></script>
<script type="text/html" id="optionTemp">
{{each result as value i}},
<option value={{value.id}}>{{value.cityName}}</option>
{{/each}}
</script>
<script type="text/html" id="weatherTemplate">
<div>
<span>当前城市:{{currentCity}}</span><br>
<span>PM2.5 : {{pm25}}</span>
</div>
{{each weather_data as value i}}
<div>
<span>{{value.date}}</span>
<ul>
<li>{{value.weather}}</li>
<li>{{value.temperature}}</li>
<li>{{value.wind}}</li>
<li><img src={{value.dayPictureUrl}} alt=""><img src={{value.nightPictureUrl}} alt=""></li>
</ul>
</div>
{{/each}}
</script>
<style type="text/css">
#info{
width: 450px;
background-color: cornflowerblue;
}
#info div{
overflow: hidden;
border-bottom: 1px solid aliceblue;
}
select{
width: 100px;
height: 28px;
}
ul li{
list-style: none;
float: left;
width: 100px;
}
</style>
</head>
<body>
<div id="container">
<select class="province"></select>
<select class="city"></select>
<select class="county"></select>
<input type="button" name="query" id="query" value="查询" /><br>
<div id="info">
</div>
</div>
<script src="./js/province-city-county.js"></script>
<script type="text/javascript">
//处理查询事件
$(function(){
$("#query").click(function(){
//var code = $("#city").val();
var county = $(".county option:selected").text();
if(county=="请选择县")
county=$(".city option:selected").text();
if(county=="请选择市"||county=="市辖区")
county=$(".province option:selected").text();
$.ajax({
url:"http://api.map.baidu.com/telematics/v3/weather?location="+county+"&output=json&ak=EGgzZ22dsboWQEcPQ6KDQLknQd3YkkkP",
//"http://www.weather.com.cn/adat/sk/"+code+".html",
type:"get",
scriptCharset: "utf-8",
dataType:"jsonp",
success:function(data){
// console.log(data.results[0]);
var html = template("weatherTemplate", data.results[0]);
$("#info").html(html);
}
});
});
});
</script>
</body>
</html>