本例用 PHP 做一個天氣預報模塊,數據採集自中國氣象網站提供的 JSON 接口。核心思路:把城市代碼列出來,前端選擇城市後把代碼提交後端,後端拼接接口 URL 取回該城市實時天氣並返回。
氣象接口示例(URL 中的數字為城市代碼):
<?php header("Content-Type:text/html;charset=utf-8"); ?>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
function $(id){ return document.getElementById(id); }
function getCityId(){
var http_request = createAjax();
var url = "weatherforecast.php";
var data = "cityid=" + $("cityId").value;
http_request.onreadystatechange = getWetherInfo;
http_request.open("post", url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.send(data);
function getWetherInfo(){
if(http_request.readyState == 4 && http_request.status == 200){
$("weatherinfo").innerHTML = http_request.responseText;
}
}
}
</script>
<select id="cityId" onchange="getCityId();">
<option>--請選擇城市--</option>
<option value="101010100">北京</option>
<option value="101020100">上海</option>
<option value="101030100">天津</option>
<option value="101040100">重慶</option>
<option value="101280101">廣州</option>
</select>
<span id="weatherinfo"></span>
<?php
header("Content-Type:text/html;charset=utf-8");
header("Cache-Control:no-cache");
if (isset($_POST['cityid'])){
$cityid = $_POST['cityid'];
$url = "https://www.weather.com.cn/data/sk/" . $cityid . ".html";
}else{
$url = "https://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'];
echo "城市名字:$cityName,氣溫:$cityTemp,風向:$cityWd";
?>
用戶切換城市觸發 Ajax 提交城市代碼,後端用 file_get_contents 抓取氣象接口、json_decode 解析後輸出天氣信息,前端無刷新地更新展示區域。