返回
PHP文件异步调用:解决天气数据更新中的城市更新问题
php
2024-03-01 15:36:56
PHP POST文件异步调用:更新天气数据
问题概述
通过PHP文件异步调用获取天气数据时,无法在表单提交后更改默认城市,导致天气数据更新不正确。
解决方案
通过POST请求更新$city
值,并使用更新后的值获取新的天气数据。
步骤
- 在
geoApi.php
中使用POST请求更新$city
值:
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['city']) && !empty($_POST['city'])) {
$city = $_POST['city'];
}
- 更新
weatherApiUrl
以使用$city
POST数据:
$weatherApiUrl = "http://api.openweathermap.org/data/2.5/weather?units=metric&q=" . $city . "&appid=" . WEATHER_API_KEY;
- 在
js_php.js
中添加代码处理POST请求:
const form = document.querySelector(".card form");
form.addEventListener("submit", (e) => {
e.preventDefault();
const city = e.target.querySelector("input").value;
fetch('http://localhost/js/weather/apis/geoApi.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
city: city
})
})
.then(response => response.json())
.then(data => {
weatherData = data;
let sky = weatherData.weather[0].main.toLowerCase();
weatherIcon.src = "images/" + sky + ".png";
console.log(weatherData);
document.querySelector(".city").innerHTML = weatherData.name;
document.querySelector(".temp").innerHTML = Math.round(weatherData.main.temp) + "°c";
document.querySelector(".humidity").innerHTML = weatherData.main.humidity + "%";
document.querySelector(".wind").innerHTML = weatherData.wind.speed + " km/h";
})
.catch((error) => {
console.error('Error:', error);
});
});
总结
通过实现上述步骤,用户提交的POST请求将更新PHP文件中的$city
值,并使用更新后的值获取新的天气数据,从而解决城市更新问题。
常见问题解答
-
为什么使用POST请求来更新城市?
POST请求可用于发送更多信息,包括敏感信息,如API密钥,而无需将其显示在URL中。 -
如何避免CORS问题?
CORS(跨域资源共享)问题可以通过启用服务器上的跨域资源共享标头来解决。 -
如何处理表单验证?
可以通过JavaScript或PHP服务器端验证来处理表单验证,以确保提交的城市有效。 -
是否可以将PHP文件部署到远程服务器?
是的,可以将PHP文件部署到远程服务器,以使其可供互联网访问。 -
如何优化天气API调用?
可以使用缓存、批处理请求和优化请求频率来优化天气API调用。