溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

PHP+AJAX如何實現(xiàn)無刷新就能返回天氣預(yù)報數(shù)據(jù)

發(fā)布時間:2021-04-09 17:34:38 來源:億速云 閱讀:193 作者:啵贊 欄目:web開發(fā)

本篇內(nèi)容介紹了“PHP+AJAX如何實現(xiàn)無刷新就能返回天氣預(yù)報數(shù)據(jù)”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

用php來寫一個天氣預(yù)報的模塊

天氣數(shù)據(jù)是通過采集中國氣象網(wǎng)站的。本來中國天氣網(wǎng)站也給出了數(shù)據(jù)的API接口。以下是API的地址。返回的數(shù)據(jù)格式為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中的數(shù)字”101010100“是城市代碼。所以可以先列出每個城市的城市代碼,然后php程序接收到了城市代碼,再去組裝URL,在通過URL來顯示該城市的實時天氣。

index.php

復(fù)制代碼 代碼如下:


<?php
header("Content-Type:text/html;charset=utf-8");
?>
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<head>
<title>weather forecast</title>
<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){
var info=http_request.responseText;
$("weatherinfo").innerHTML=info;
}
}
}
</script>
</head>
<body>
<select name="cityId" onchange="getCityId();" id="cityId">
<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>
</body>
</html>


weatherforecast.php

復(fù)制代碼 代碼如下:


<?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,風(fēng)向:$cityWd";
?>

“PHP+AJAX如何實現(xiàn)無刷新就能返回天氣預(yù)報數(shù)據(jù)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI