当前位置:编程学习 > JAVA >>

天气预报的Ajax效果

 最近在网站上看了很多显示实时天气预报的,挺实用而且用户体验也不错。对用户的帮助也比较大,用户可以通过你的网站了解到实时的天气信息。感觉比较有意思,于是自己钻研了一下其中的实现方法。于是决定把代码分享给大家,希望能对大家的前端事业有所贡献。

  原理其实很简单。就是当页面加载进来之后,请求php文件,返回一组json。这组json就是我们所需要的有关天气的信息。我们只需要把返回来的json解析以后,放到相应的位置即可。

  JavaScript的代码:


[javascript] 
$(function  () { 
     
    $.ajax({ 
        //请求的地址  
        url : "weather.php", 
        //请求成功后执行的函数  
        success : function  (data) { 
 
            //用eval()解析返回来的数据,将字符串转成JSON格式  
            var oD = eval('('+data+')'); 
             
            //用jquery-1.8.2获取元素  
            var $place = $(".place"), 
                $temp = $(".temp"), 
                $wind = $(".wind"), 
                $windPower = $(".windPower"); 
             
            //将返回来的数据放到相应的位置  
            $place.html(oD["weatherinfo"]["city"]); 
            $temp.html(oD["weatherinfo"]["temp"] + "°"); 
            $wind.html(oD["weatherinfo"]["WD"]); 
            $windPower.html(oD["weatherinfo"]["WS"]); 
 
        } 
    }); 
     
}) 

$(function  () {
 
 $.ajax({
  //请求的地址
  url : "weather.php",
  //请求成功后执行的函数
  success : function  (data) {

   //用eval()解析返回来的数据,将字符串转成JSON格式
   var oD = eval('('+data+')');
   
   //用jquery-1.8.2获取元素
   var $place = $(".place"),
    $temp = $(".temp"),
    $wind = $(".wind"),
    $windPower = $(".windPower");
   
   //将返回来的数据放到相应的位置
   $place.html(oD["weatherinfo"]["city"]);
   $temp.html(oD["weatherinfo"]["temp"] + "°");
   $wind.html(oD["weatherinfo"]["WD"]);
   $windPower.html(oD["weatherinfo"]["WS"]);

  }
 });
 
})

 

  由于是从其他网站上面取数据,所以用了点php的小知识。PHP的思路是用file_get_contents()函数向指定的地址请求,返回来的数据再输出到前台。

  PHP代码:


[php] 
<?php 
    $weather = file_get_contents("http://www.weather.com.cn/data/sk/101010100.html"); 
    echo $weather; 
?> 

<?php
 $weather = file_get_contents("http://www.weather.com.cn/data/sk/101010100.html");
 echo $weather;
?>


  HTML代码:


[html] 
<div class="all"> 
    这里是:<span class="place">城市</span>, 
    气温是<span class="temp">气温</span>, 
    风向:<span class="wind">风向</span>, 
    风力:<span class="windPower">风力</span> 
</div> 

<div class="all">
 这里是:<span class="place">城市</span>,
 气温是<span class="temp">气温</span>,
 风向:<span class="wind">风向</span>,
 风力:<span class="windPower">风力</span>
</div>


  为了使页面看得比较清楚,加了些样式。

  Css代码:


[css] 
 
.all span {font:bold 30px/50px "宋体";color:red;} 


.all span {font:bold 30px/50px "宋体";color:red;}

 

  以上就是简单的天气预报效果,还有一些简单的原理实现。希望能对大家的前端事业有一些小小的帮助。以上仅是个人理解,若有小问题,咱们可以随时交流,互相学习嘛。

 

 

补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,