好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

php ajax实现无刷新获取天气状态 - php高级应用

php ajax实现无刷新获取天气状态

首先我们要明白一点我们自己是无法来做天气预报这种功能的,这里我们只要调用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 ( empty empty ( $citycode )){     echo   "您输入的城市不在范围内" ;   } else {     echo   file_get_contents ( "http://www.weather.com.cn/data/cityinfo/" . $citycode . ".html" );   }  ?> 

查看更多关于php ajax实现无刷新获取天气状态 - php高级应用的详细内容...

  阅读:33次