首先我們要明白一點我們自己是無法來做天氣預報這種功能的,這里我們只要調用api接口返回的數據就可以了,下面是以中國天氣網的api接口調用實例我們一起來學習,天氣已經成為生活中不可缺少的話題,與我們的生活有著密切的關系,我博客右邊就用php+ajax做了一個天氣查詢小模塊。
理想的狀態應該是用戶根據不同的訪問地自動獲取當地的天氣信息,但是暫時技術有限吧,只能完成手動查詢的了,這個就簡單多了,沒用到過多的技術,主要是應用ajax調用一個開放接口,然后再處理一下返回的json數據就完成了。
接口地址:http://www.weather.com.cn/data/cityinfo/101200101.html
返回的值:{"weatherinfo":{"city":"武漢","cityid":"101200101","temp1":"28℃","temp2":"36℃","weather":"晴轉多云","img1":"n0.gif","img2":"d1.gif","ptime":"18:00"}}
接口地址部分“101200101”,這串ID號是城市ID,我百度到城市對應的id,然后封裝成了一個數組,用的時候直接調用就行了。核心代碼也不多,主要是城市——ID比較大,我就不貼源碼了,直接打包分享出來吧。需要的朋友直接下載就行了!
部份代碼如下:
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <script type="text/javascript" src="jquery.js" ></script>
- <script type="text/javascript">
- $(function(){
- $("#submit").click(function(){
- //發送ajax請求
- var city = $("#city").val();
- $.post("getweather.php", {city:city}, function(data){
- if(data.weatherinfo.city){
- var city = data.weatherinfo.city; //城市名稱
- var temp1 = data.weatherinfo.temp1; //最高氣溫
- var temp2 = data.weatherinfo.temp2; //最低氣溫
- var weather = data.weatherinfo.weather; //天氣描述(“晴到多云”)
- alert(city+":"+weather+","+temp2+"-"+temp1);
- return;
- }else{
- alert("沒找到該城市");
- }
- },"json");
- });
- });
- </script>
getweather.php文件代碼如下:
- <form method="post">
- 請輸入城市:<input type="text" name="city" id="city" value="武漢" />
- <input type="button" name="sub" id="submit" value="查看天氣" />
- </form>
- <?php
- include "citycode.php";
- $city = $_POST['city'];
- $citycode = @$citycode[$city];
- //echo "shibushi";
- if(emptyempty($citycode)){
- echo "您輸入的城市不在范圍內";
- }else{
- echo file_get_contents("http://www.weather.com.cn/data/cityinfo/".$citycode.".html");
- }
- ?>
新聞熱點
疑難解答