首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 結合 jQuery 實作即時天氣預報顯示

     編輯:PHP 綜合知識

後端 PHP 代理呼叫氣象 API,前端 jQuery AJAX 非同步取得並動態更新頁面。

後端 weather.php

<?php
header("content-type:text/html;charset=utf-8");
echo file_get_contents("https://www.weather.com.cn/data/sk/101280601.html");
?>

前端 HTML + jQuery

<div class="all">
這裡是:<span class="place">城市</span>, 氣溫<span class="temp">氣溫</span>,
風向:<span class="wind">風向</span>, 風力:<span class="windPower">風力</span>
</div>
<script src="jquery.js"></script>
<script>
$(function(){
    $.ajax({
        url: "weather.php",
        success: function(data){
            var oD = eval('('+data+')'); // 解析 JSON
            $(".place").html(oD["weatherinfo"]["city"]);
            $(".temp").html(oD["weatherinfo"]["temp"] + "°");
            $(".wind").html(oD["weatherinfo"]["WD"]);
            $(".windPower").html(oD["weatherinfo"]["WS"]);
        }
    });
});
</script>

畫面示意

天氣預報畫面

注意

  • 示範使用 eval 解析 JSON,現代專案建議用 JSON.parse 或 jQuery 內建 dataType:'json'。
  • 氣象 API 端點可能失效,請替換為可用來源。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved