如何在网页上显示异步函数获取的结果



编写了一段js代码,从URL获取API数据,并希望将其集成到网页中以显示结果。

来自URL的源API看起来像:

{"region_metadata":[{"name":"west","label_location":{"latitude":1.35735,"longitude":103.7}},{"name":"east","label_location":{"latitude":1.35735,"longitude":103.94}},{"name":"central","label_location":{"latitude":1.35735,"longitude":103.82}},{"name":"south","label_location":{"latitude":1.29587,"longitude":103.82}},{"name":"north","label_location":{"latitude":1.41803,"longitude":103.82}}],"items":[{"timestamp":"2020-02-28T15:00:00+08:00","update_timestamp":"2020-02-28T15:08:52+08:00","readings":{"pm25_one_hourly":{"west":3,"east":8,"central":9,"south":10,"north":8}}}],"api_info":{"status":"healthy"}}

我有以下代码在JavaScript中工作:

async function getdata() {
const fetch = require("node-fetch")
let response = await fetch('https://api.data.gov.sg/v1/environment/pm25')
let data = await response.json()
return data
};
const resulteast = getdata().then(data => data.items[0].readings.pm25_one_hourly);
var valueeast = Promise.resolve(resulteast)
valueeast.then(data => {
array = data    
console.log(array)
});

这在console.log中给出以下结果:

{ west: 10, east: 9, central: 10, south: 11, north: 3 }

现在我想在网页中显示这个结果。类似这样的东西:

<p id="value"></p>
<script>
// Fetch data from remote website
async function getdata() {
const fetch = require("node-fetch")
let response = await fetch('https://api.data.gov.sg/v1/environment/pm25')
let data = await response.json()
return data
};
const resulteast = getdata().then(data => data.items[0].readings.pm25_one_hourly);
var valueeast = Promise.resolve(resulteast)
valueeast.then(data => {
array = data    
document.getElementById("value").innerHTML = "South " + array
});
</script>

我在网页上没有得到任何结果。

我是否在正确的位置调用document.getElementById?我似乎无法从箭头函数的promise out侧得到响应。因为我可以在网页上显示其他变量。

请告知!

// Fetch data from remote website
async function getdata() {
// const fetch = require("node-fetch")
let response = await fetch('https://api.data.gov.sg/v1/environment/pm25')
let data = await response.json()
return data
};
const resulteast = getdata().then(data => data.items[0].readings.pm25_one_hourly);
var valueeast = Promise.resolve(resulteast)
valueeast.then(data => {
array = data
document.getElementById("value").innerHTML =  JSON.stringify(array);
});
<p id="value"></p>

如果您想以相同的方式打印,可以使用此代码{西:10,东:9,中:10,南:11,北:3}

不能将数组或对象追加到网页,只能追加字符串

document.getElementById("value").innerHTML = "South " + array["south"];

对不起,我误解了你的问题。

最新更新