javascript - 如何将 API 响应插入 HTML

标签 javascript json api async-await pure-function

我使用纯函数为多个 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()));
}

渲染后的预期: a busy cat
(来源: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/

相关文章:

javascript - Bootstrap : Search Icon Button Inside Input Box separates from Inputbox at non-desktop Resolution

json - Protocol和Json Wire Protocol有什么区别

json - Golang解析复杂的json

android - Android 版 Facebook SDK

调用 web 服务时 iOS 错误,找不到具有指定主机名的服务器

javascript - 正则表达式括号中的特殊字符

javascript - 是否可以使用正则表达式去除字符串中超过 X 位的数字?

javascript - 根据数据库结果重新定义动态路由

javascript - 如何使用 JSON Schema 验证表单?

java - 为什么我的代码从嵌套的 JSON 数组返回值 'null'