您现在的位置是:网站首页> 编程资料编程资料
PHP+AJAX无刷新实现返回天气预报数据_AJAX相关_
2023-05-25
239人已围观
简介 PHP+AJAX无刷新实现返回天气预报数据_AJAX相关_
用php来写一个天气预报的模块
天气数据是通过采集中国气象网站的。本来中国天气网站也给出了数据的API接口。以下是API的地址。返回的数据格式为json格式。
1. http://www.weather.com.cn/data/sk/101010100.html
2. http://www.weather.com.cn/data/cityinfo/101010100.html
3. http://m.weather.com.cn/data/101010100.html
URL中的数字”101010100“是城市代码。所以可以先列出每个城市的城市代码,然后php程序接收到了城市代码,再去组装URL,在通过URL来显示该城市的实时天气。
index.php
header("Content-Type:text/html;charset=utf-8");
?>
weather forecast
weatherforecast.php
header("Content-Type:text/html;charset=utf-8");
header("Cache-Control:no-cache");
if (isset($_POST['cityid'])){
$cityid=$_POST['cityid'];
$url=$url="http://www.weather.com.cn/data/sk/".$cityid.".html";
}else {
$url="http://www.weather.com.cn/data/sk/101010100.html";
}
$weatherInfo_json=file_get_contents($url);
$weatherInfo=json_decode($weatherInfo_json,true);
$cityName=$weatherInfo['weatherinfo']['city'];
$cityTemp=$weatherInfo['weatherinfo']['temp'];
$cityWd=$weatherInfo['weatherinfo']['WD'];
$cityWs=$weatherInfo['weatherinfo']['WS'];
$cityTime=$weatherInfo['weatherinfo']['time'];
$citySD=$weatherInfo['weatherinfo']['SD'];
echo $weatherinfo="城市名字:$cityName,气温:$cityTemp,风向:$cityWd";
?>
天气数据是通过采集中国气象网站的。本来中国天气网站也给出了数据的API接口。以下是API的地址。返回的数据格式为json格式。
1. http://www.weather.com.cn/data/sk/101010100.html
2. http://www.weather.com.cn/data/cityinfo/101010100.html
3. http://m.weather.com.cn/data/101010100.html
URL中的数字”101010100“是城市代码。所以可以先列出每个城市的城市代码,然后php程序接收到了城市代码,再去组装URL,在通过URL来显示该城市的实时天气。
index.php
复制代码 代码如下:
header("Content-Type:text/html;charset=utf-8");
?>
weatherforecast.php
复制代码 代码如下:
header("Content-Type:text/html;charset=utf-8");
header("Cache-Control:no-cache");
if (isset($_POST['cityid'])){
$cityid=$_POST['cityid'];
$url=$url="http://www.weather.com.cn/data/sk/".$cityid.".html";
}else {
$url="http://www.weather.com.cn/data/sk/101010100.html";
}
$weatherInfo_json=file_get_contents($url);
$weatherInfo=json_decode($weatherInfo_json,true);
$cityName=$weatherInfo['weatherinfo']['city'];
$cityTemp=$weatherInfo['weatherinfo']['temp'];
$cityWd=$weatherInfo['weatherinfo']['WD'];
$cityWs=$weatherInfo['weatherinfo']['WS'];
$cityTime=$weatherInfo['weatherinfo']['time'];
$citySD=$weatherInfo['weatherinfo']['SD'];
echo $weatherinfo="城市名字:$cityName,气温:$cityTemp,风向:$cityWd";
?>
您可能感兴趣的文章:
相关内容
- jquery ajax 向后台传递数组参数示例_AJAX相关_
- IIS7中Ajax.AjaxMethod无效的原因及解决方法_AJAX相关_
- ajax读取数据库内容实现二级联动下拉选择菜单示例_AJAX相关_
- AJAX在不同浏览器中XMLHttpRequest对象的生成示例_AJAX相关_
- asp.net中mvc使用ajax提交参数的匹配问题解决探讨_AJAX相关_
- ajax 防止用户反复提交的2种解决方案_AJAX相关_
- 添加后台list给前台select标签赋值简单实现_AJAX相关_
- ajax返回的json内容进行排序使用sort()方法实现_AJAX相关_
- 用juery的ajax方法调用aspx.cs页面中的webmethod方法示例_AJAX相关_
- Ajax 说的比较清楚的一篇文章_AJAX相关_
