Javascript 获取后在网页中加载数据
我试图从API获取数据,然后在网页中设置数据。应在呈现页面之前设置数据 HTML代码:Javascript 获取后在网页中加载数据,javascript,html,css,dom,fetch,Javascript,Html,Css,Dom,Fetch,我试图从API获取数据,然后在网页中设置数据。应在呈现页面之前设置数据 HTML代码: <div id="info"> <h1 id="p_name"></h1> <h2> <a href="" id="p_spec"></a> </h2> <h3 id="p_number
<div id="info">
<h1 id="p_name"></h1>
<h2>
<a href="" id="p_spec"></a>
</h2>
<h3 id="p_numberp"></h3>
<img id="p_image">
</div>
我尝试了这个方法,但不起作用(当我打开网页时,所有项目都未定义)。
谢谢。您有两个选择: 回调调用必须在then调用中 或者你必须使用wait关键字
async function fetchdata(id, callback) {
url = "https://my_url" + id;
fetch(url)
.then((resp) => {
page_data = resp.json();
callback();
})
}
注意,当我们使用fetch时,我们应该检查响应是否为“OK”大概是这样的:
async function fetchdata(id, callback) {
url = "https://my_url" + id;
// when using async calls we use await before calling a promise
await fetch(url).then((resp) => page_data = resp.json())
callback();
}
在上阅读更多关于它的信息这是否回答了您的问题?这是您的代码,已修复:
async function fetchdata(id, callback) {
url = "https://my_url" + id;
// when using async calls we use await before calling a promise
await fetch(url).then((resp) => page_data = resp.json())
callback();
}
.then((resp) => {
if (!resp.ok) return; // or do something else
page_data = resp.json();
callback();
})