我使用纯函数为多个 HTML 元素创建包装器,但不明白如何将 JSON 响应 API 数据插入其中。 您能否帮助创建一个将 API 数据像文本一样插入到 HTML 中的纯函数,或者使用名为“create”且具有“innerText”属性的现有函数。
我发现类似的问题: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;
};
API:
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()));
}
渲染后的预期:
(来源:androidheadlines.com)
预期为 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}
最佳答案
您的 HTML 不会知道如何处理 json
。您需要明确告诉您的 html 这些值是什么。例如:
async function showData() {
const main = document.querySelector("#main");
document.body.appendChild(main);
const obj = parser(await request()); // <-- Assuming this works and it returns an object (not json)
// Give your elements Id's to make it easier
document.getElementById('time').innerText = obj.time;
...
}
如果我误解了,您只是想将实际的 json
打印到网页上,那么您
async function showData() {
const main = document.querySelector("#main");
document.body.appendChild(main);
const obj = parser(await request()); // <-- Assuming this works
main.innerText = JSON.stringify(obj, null, 2);
}
如果您尝试将字符串化的 json 打印到页面,我还建议使用 pre
标记。
关于javascript - 如何将 API 响应插入 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55737241/