我爱模板网在做一个HTML5 APP项目时,需要在APP头部显示当前城市的天气,这个简单啊,首先获取当前城市,可以使用下面的代码(这是html5+,当然html5也可以获取):
plus.geolocation.getCurrentPosition(function(p){
var city = p.address.city;
getWeather(city);
}, function(e){
return 'Geolocation error: ' + e.message;
});
调用天气信息接口:
function getWeather(city){
var xhr = new XMLHttpRequest;
xhr.open('get','http://wthrcdn.etouch.cn/weather_mini?city='+city);
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
document.write(xhr.responseText);
}
}
}
}
得到的结果:
{
"data": {
"yesterday": {
"date": "2日星期三",
"high": "高温 26℃",
"fx": "北风",
"low": "低温 13℃",
"fl": "",
"type": "多云"
},
"city": "合肥",
"aqi": "69",
"forecast": [{
"date": "3日星期四",
"high": "高温 26℃",
"fengli": "",
"low": "低温 13℃",
"fengxiang": "西北风",
"type": "晴"
}, {
"date": "4日星期五",
"high": "高温 27℃",
"fengli": "",
"low": "低温 17℃",
"fengxiang": "南风",
"type": "多云"
}, {
"date": "5日星期六",
"high": "高温 24℃",
"fengli": "",
"low": "低温 18℃",
"fengxiang": "西南风",
"type": "小雨"
}, {
"date": "6日星期天",
"high": "高温 24℃",
"fengli": "",
"low": "低温 16℃",
"fengxiang": "北风",
"type": "中雨"
}, {
"date": "7日星期一",
"high": "高温 20℃",
"fengli": "",
"low": "低温 16℃",
"fengxiang": "东北风",
"type": "多云"
}],
"ganmao": "昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。",
"wendu": "21"
},
"status": 1000,
"desc": "OK"
}
返回了近几天很多实用的天气信息,可以使用了!