Javascript 如何根据“获取”结果创建“li”

Javascript 如何根据“获取”结果创建“li”,javascript,Javascript,我试图通过参考他们的文档从这个网站上获取一些数据 我正在尝试检索犬种列表并创建一个列表。我正在使用javaScript的fetch let dog_list=[]; 取回https://dog.ceo/api/breeds/list/all' .thenresponse=>{ 如果回答是肯定的{ return response.json; }否则{ 抛出新的Errorresponse.statusText; } } .thendata=>dog_list=data.message const

我试图通过参考他们的文档从这个网站上获取一些数据

我正在尝试检索犬种列表并创建一个列表。我正在使用javaScript的fetch

let dog_list=[]; 取回https://dog.ceo/api/breeds/list/all' .thenresponse=>{ 如果回答是肯定的{ return response.json; }否则{ 抛出新的Errorresponse.statusText; } } .thendata=>dog_list=data.message const container=document.getElementByIdcontainer; 狗在狗的名单上{ 设li=document.createElementli; 让节点=document.createTextNodedog; li.childnode; 容器。附属物; } 犬种表 只需在回调中构造你的li,在那里你可以创建dog_列表

像这样的

let dog_list = [];
const container = document.getElementById("container");
fetch('https://dog.ceo/api/breeds/list/all')
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error(response.statusText);
        }
    })
    .then(data => {
        dog_list = data.message;
        for (dog in dog_list) {
            let li = document.createElement("li");
            let node = document.createTextNode(dog);
            li.appendChild(node);
            container.appendChild(li);
        }
    });

为什么需要在promise处理程序中构造结果DOM结构? 因为整个 fetch/*…*/。然后/*…*/。然后将执行/*…*块

在不等待代码完成的情况下,主线“全局”代码将从之后的行继续执行,在您的情况下,这将获取容器并开始添加li元素。问题是,此时,即使执行了fetch并返回了结果,fetch调用的响应处理也不会启动,因此dog_列表将为空。

因为中的回调是异步的,您可以在中填充列表。否则,在循环运行时,dog_列表仍将是空数组:

取回https://dog.ceo/api/breeds/list/all' .thenresponse=>{ 如果回答是肯定的{ return response.json; }否则{ 抛出新的Errorresponse.statusText; } } .thendata=>populatedata.message; 函数填充的日志列表{ const container=document.getElementByIdcontainer; 狗在狗的名单上{ 设li=document.createElementli; 让节点=document.createTextNodedog; li.childnode; 容器。附属物; } } 犬种表
您也可以使用async和Wait尝试同样的方法。 请看下面

常量url=https://dog.ceo/api/breeds/list/all'; 异步函数主{ const dog_data=wait getDogDataurl.catchError; const dog_list=dog_data.message; const container=document.getElementByIdcontainer; 狗在狗的名单上{ const node=createHtmleElement'li',dog; container.appendChildnode; } } 函数catchErrorerr{ console.log'Error',err; } 函数createHtmleElement_节点,数据{ 设li=document.createElementli; li.textContent=狗; 返回李; } 异步函数getDogData\u url{ const response=wait fetch\u url; return wait response.json; } 主要的 犬种表
在回调内移动for循环的可能重复项。thendata=>{dog_list=data.message;const container=document.getElementByIdcontainer;对于dog_list{….}中的dog,您的循环在抓取dog之前运行。哇,在这之后的读取位置上有一个清晰的路径,我在JS中还是比较新的,从不知道异步和等待的存在。感谢您的介绍。感谢您将填充部分分离到另一个函数中以实现可维护性。