PHP Ajax JavaScript Json获取天气信息实现代码

时间:2021-05-26

要在自己的网站上添加一个天气预报功能,是一个很普通的需求,实现起来也不是很难。今天来介绍几个简单的方法。

使用第三方服务

有这样的一种简单的方式,借助http://.cn/adat/sk/".$city_id."html";$weather = file_get_contents($weather_url);echo $weather;?>

前端完整代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>获取天气信息</title><script>function getinfo(){ var ajax = new XMLHttpRequest(); ajax.onreadystatechange = function(){ if(ajax.readyState==4){ alert(ajax.responseText); eval("var data=" + ajax.responseText); alert(data); document.getElementById("city").innerHTML =data.weatherinfo.city; document.getElementById("cityid").innerHTML =data.weatherinfo.cityid; document.getElementById("temp").innerHTML =data.weatherinfo.temp; document.getElementById("WD").innerHTML =data.weatherinfo.WD; document.getElementById("WS").innerHTML =data.weatherinfo.WS; document.getElementById("SD").innerHTML =data.weatherinfo.SD; document.getElementById("time").innerHTML =data.weatherinfo.time; } } ajax.open('get','./getinfo.php'); ajax.send(null);}</script></head><body><h3>获取城市代码</h3><button type="button" onclick="getcitycode()">获取城市代码</button><br /><script> function getcitycode(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState==4){ //alert(xhr.responseText); eval('var citycode='+xhr.responseText); alert(citycode.data.city); } } xhr.open('get','./getcityid.php'); xhr.send(null); }</script><span id="cityid"></span><h3>点击按钮获取天气信息</h3><button name="getinfo" onclick="getinfo()">获取</button><div><span>城市名称</span><span id="city"></span><br /><span>城市代码</span><span id="cityid"></span><br /><span>当前温度</span><span id="temp"></span><br /><span>风向</span><span id="WD"></span><br /><span>风速</span><span id="WS"></span><br /><span>湿度</span><span id="SD"></span><br /><span>更新时间</span><span id="time"></span><br /></div></body></html>

总结

在自己的网站上添加一个天气预报功能,其实并不难。也许还有更为简单的方式,这里就算是一个抛砖引玉的过程吧。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章