1

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

1 回答 1

1

您的 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标签。

于 2019-04-17T23:40:37.507 回答