Home >php教程 >php手册 >php ajax实现无刷新获取天气状态

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-02 09:14:27809browse

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

测试效果


 

源码下载:http://www.phprm.com:

 

文章地址:

转载随意^^请带上本文地址!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP定时跳转 Next article:php mysql 查询数据库