我正在尝试制作一个天气应用程序,显示一周中许多天的天气和温度。我目前正在使用 openweathermap api 来完成此类任务,问题是我想要的信息(即天气日期)仅采用 xml 格式。
由于我出于学术原因在 ES6(ES2015) 中重建它,我还想使用 fetch api,但由于 fetch 方法解析它,它只是传递一个错误。
那么我怎样才能获取它或者有更好的方法来做到这一点。
let apis = {
currentWeather: { //get user selected recomendation weather
api:"http://api.openweathermap.org/data/2.5/forecast/daily?lat=",
parameters: "&mode=xml&units=metric&cnt=6&APPID=/*api key*/",
url: (lat, lon) => {
return apis.currentWeather.api + lat + "&lon=" + lon +
apis.currentWeather.parameters
}
}
};
function getCurrentLoc() {
return new Promise((resolve, reject) => navigator.geolocation
.getCurrentPosition(resolve, reject))
}
function getCurrentCity(location) {
const lat = location.coords.latitude;
const lon = location.coords.longitude;
return fetch(apis.currentWeather.url(lat, lon))
.then(response => response.json())
.then(data => console.log(data))
}
getCurrentLoc()
.then( coords => getCurrentCity(coords))
使用原生 DOMParser getCurrentCity(location) 可以写成:
function getCurrentCity(location) {
const lat = location.coords.latitude;
const lon = location.coords.longitude;
return fetch(apis.currentWeather.url(lat, lon))
.then(response => response.text())
.then(str => new window.DOMParser().parseFromString(str, "text/xml"))
.then(data => console.log(data));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)