DIV CSS 佈局教程網

PHP + Ajax 無刷新實現查詢天氣預報數據
編輯:AJAX基礎知識     

本例用 PHP 做一個天氣預報模塊,數據採集自中國氣象網站提供的 JSON 接口。核心思路:把城市代碼列出來,前端選擇城市後把代碼提交後端,後端拼接接口 URL 取回該城市實時天氣並返回。

氣象接口示例(URL 中的數字為城市代碼):

  • https://www.weather.com.cn/data/sk/101010100.html
  • https://www.weather.com.cn/data/cityinfo/101010100.html
  • https://m.weather.com.cn/data/101010100.html

index.php

<?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>

weatherforecast.php

<?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 解析後輸出天氣信息,前端無刷新地更新展示區域。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved