我使用纯函数为多个 HTML 元素创建包装器,但不明白如何将 JSON 响应 API 数据插入其中。您能否帮助创建一个将 API 数据插入 HTML 之类的纯函数(如文本)或使用具有属性“innerText”的名为“create”的现有函数。
我发现了类似的问题:Using Javascript loop to create multiple HTML elements
const create = (what, classAndId, text) => {
let element = document.createElement(what);
element.className = classAndId.class;
element.id = classAndId.id;
element.innerText = text;
return element;
};
接口:
const link = `http://api.apixu.com/v1/current.json?key=${key}&q=Kiev`;
const request = async () => {
try {
const response = await fetch(link);
return await response.json();
}catch (e) {
throw new Error(e);
}
};
将 API 数据转换为可读格式的函数:
const parser = param => {
return {
name: param.location.name,
region: param.location.country,
time: param.location.localtime,
temperature: {
real: param.current.temp_c,
feels_like: param.current.feelslike_c,
},
wind: {
speed: param.current.wind_kph,
direction: param.current.wind_dir,
},
pressure: param.current.pressure_mb,
visibility: param.current.vis_km,
precipitation: param.current.precip_mm,
humidity: param.current.humidity,
};
};
转换后仅将 API 数据呈现为 HTML 的异步函数:
async function showData() {
const main = document.querySelector("#main");
document.body.appendChild(main);
main.innerHTML = JSON.stringify(parser(await request()));
}
渲染后预期:
预期为 HTML:
<div class="item">11:30 PM</div>
<div class="item">Mostly Cloud</div>
<div class="item">Thu Jun 13</div>
那确实渲染功能:
{"name":"Kiev","region":"Ukraine","time":"2019-04-18 1:38","temperature":{"real":6,"feels_like":4.6},"wind":{"speed":6.8,"direction":"ENE"},"pressure":1028,"visibility":10,"precipitation":0,"humidity":70}