AJAX+PHP獲取天氣預報API案例
阿新 • • 發佈:2018-11-15
AJAX+PHP獲取天氣預報API案例
PHP程式碼獲取API程式碼:
<?php
//宣告utf-8編碼標頭檔案
header('Content-type:text/html;charset=utf-8');
$tou = file_get_contents("http://f.yohall.com/apics-tq.html?city=" . $_GET['city']);
$arr = json_decode($tou, true); // JSON資料轉PHP陣列(true)
echo json_encode($arr); /* 以 JSON 字串型別輸出 */
Js程式碼如下:
// 使用原生AJAX 利於封裝 調取資訊;
var xhr;
function show(url, crl) {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = crl;
xhr.open("get", url);
xhr.send();
}
add(); /* 設定預設載入*/
function add() {
val = document.getElementById("xl").value;
// 獲取 select下拉選單的值;
show("./new.php?city=" + val, function () {
if (xhr.readyState !== 4) return
data = xhr.responseText;
eval("var obj=" + data);
day = obj.results[0].weather_data;
$("#img").attr("src", day[0].dayPictureUrl);
// 下面 可以輸出檢視作為參考 無意義!
$(".wd").text(day[0].temperature);
$(".wd_1").text(day[1].temperature);
$(".wd_2"). text(day[2].temperature);
$(".wd_3").text(day[3].temperature);
$(".wet").text(day[0].weather);
$(".weat_1").text(day[1].weather);
$(".weat_2").text(day[2].weather);
$(".weat_3").text(day[3].weather);
$(".city").text(obj.results[0].currentCity);
$(".pm").html("pm2.5:" + obj.results[0].pm25);
$(".win").text(day[0].wind);
$(".date").text(day[0].date);
$(".day_1").text(day[1].date);
$(".day_2").text(day[2].date);
$(".day_3").text(day[3].date);
})
}
// 給select繫結 change改變事件,調取add函式執行onreadystatechange;
document.getElementById("xl").addEventListener("change", add);
案例樣式:
目前只開放了三個城市,可以作為參考,望熱心網友提出寶貴意見
連結:https://www.cwenz.cn/mini/tianqi/new.html