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比较大,我就不贴源码了,直接打包分享出来吧。需要的朋友直接下载就行了!
部份代码
<table style="background: #fb7" border="0" cellspacing="1" cellpadding="1" width="620" align="center"> <tbody> <tr> <td bgcolor="#ffe7ce" height="27" width="464"> 代码如下</td> <td style="cursor: pointer" bgcolor="#ffe7ce" width="109" align="center" onclick="doCopy('copy4131')">复制代码</td> </tr> <tr> <td style="padding-bottom: 10px; padding-left: 10px; padding-right: 10px; padding-top: 10px" id="copy4131" class="copyclass" bgcolor="#ffffff" valign="top" colspan="2">
<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文件
<table style="background: #fb7" border="0" cellspacing="1" cellpadding="1" width="620" align="center"> <tbody> <tr> <td bgcolor="#ffe7ce" height="27" width="464"> 代码如下</td> <td style="cursor: pointer" bgcolor="#ffe7ce" width="109" align="center" onclick="doCopy('copy7352')">复制代码</td> </tr> <tr> <td style="padding-bottom: 10px; padding-left: 10px; padding-right: 10px; padding-top: 10px" id="copy7352" class="copyclass" bgcolor="#ffffff" valign="top" colspan="2"><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($citycode)){
echo "您输入的城市不在范围内";
}else{
echo file_get_contents("http://www.weather.com.cn/data/cityinfo/".$citycode.".html");
}
?>
测试效果
源码下载:php ajax实现无刷新获取天气状态源码下载:
您可能感兴趣的文章:
php ajax实现无刷新获取天气状态
Google API 获取当前天气信息的php代码
php百度天气小偷实现代码
AJAX在PHP中的简单使用
php页面不刷新更新数据
用Jquery实现多级下拉框无刷新的联动
php js ajax实现简单的回帖功能
PHP调用百度天气接口API实现查询实时天气
PHP数据采集程序采集天气网数据实例演示
ajax实现局部刷新页面--留言刷新