AJAX+PHP获取天气预报API案例

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
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41717244/article/details/83689885