从 Javascript 输出 HTML 表时出现问题

发布于 2025-01-10 17:12:07 字数 1770 浏览 0 评论 0原文

我正在尝试从外部 json 文件引入数据,并使用它来生成表。我在第 52 行遇到问题 'Uncaught TypeError: Cannot conversion undefined or null to object at Function.keys' 。当我注释掉前 2 个异步函数时,使用“山”变量中的示例数据并引用“山”而不是 html 表按预期生成的用户。我认为问题与我的第二个异步函数有关,但我是一个不知所措的新手。任何帮助表示赞赏!

async function getUsers() {
    let url = '../assets/names.json';
    try {
        let res = await fetch(url);
        return await res.json(); 
    } catch (error) {
        console.log(error)
    }
}

async function users() {
    
    let users = await getUsers()                        
 
}


/* let mountains = [
    { name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
    { name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" },
    { name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
    { name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
    { name: "Monte Amiata", height: 1738, place: "Siena" }
  ];
  */



  function generateTableHead(table, data) {
    let thead = table.createTHead();
    let row = thead.insertRow();
    for (let key of data) {
      let th = document.createElement("th");
      let text = document.createTextNode(key);
      th.appendChild(text);
      row.appendChild(th);
    }
  }
  
  function generateTable(table, data) {
    for (let element of data) {
      let row = table.insertRow();
      for (key in element) {
        let cell = row.insertCell();
        let text = document.createTextNode(element[key]);
        cell.appendChild(text);
      }
    }
  }
  
  let table = document.querySelector("table");
  let data = Object.keys(users[0]);
  generateTableHead(table, data);
  generateTable(table, users);

I'm trying to bring in data from an external json file, and use it to generate a table. I'm running into a problem on line 52 'Uncaught TypeError: Cannot convert undefined or null to object at Function.keys' . When I comment out the first 2 async functions, use the sample data in the 'mountains' variable and reference 'mountains' instead of users the html table generates as expected. I think the problem has to do with my 2nd async function but I'm a newbie at a loss. Any help appreciated!

async function getUsers() {
    let url = '../assets/names.json';
    try {
        let res = await fetch(url);
        return await res.json(); 
    } catch (error) {
        console.log(error)
    }
}

async function users() {
    
    let users = await getUsers()                        
 
}


/* let mountains = [
    { name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
    { name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" },
    { name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
    { name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
    { name: "Monte Amiata", height: 1738, place: "Siena" }
  ];
  */



  function generateTableHead(table, data) {
    let thead = table.createTHead();
    let row = thead.insertRow();
    for (let key of data) {
      let th = document.createElement("th");
      let text = document.createTextNode(key);
      th.appendChild(text);
      row.appendChild(th);
    }
  }
  
  function generateTable(table, data) {
    for (let element of data) {
      let row = table.insertRow();
      for (key in element) {
        let cell = row.insertCell();
        let text = document.createTextNode(element[key]);
        cell.appendChild(text);
      }
    }
  }
  
  let table = document.querySelector("table");
  let data = Object.keys(users[0]);
  generateTableHead(table, data);
  generateTable(table, users);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

舟遥客 2025-01-17 17:12:07

由于 fetch 是异步的,因此您只需在 fetch 接收到数据后就需要处理数据

这应该给您一个想法

async function getUsers() {
    let url = '../assets/names.json';
    try {
        let res = await fetch(url);
        return res.json();
    } catch (error) {
        console.log(error);
    }
}
async function fakeGetUsers() {
    // fake delay
    await new Promise(res => setTimeout(res, 1000));
    // simulate return res.json();
    return [{name:"Monte Falco",height:1658,place:"Parco Foreste Casentinesi"}, {name:"Monte Falterona",height:1654,place:"Parco Foreste Casentinesi"}, {name:"Poggio Scali",height:1520,place:"Parco Foreste Casentinesi"}, {name:"Pratomagno",height:1592,place:"Parco Foreste Casentinesi"}, {name:"Monte Amiata",height:1738,place:"Siena"}];
}
async function users() {
    const users = await fakeGetUsers();
    // here you can use the data
    function generateTableHead(table, data) {
        let thead = table.createTHead();
        let row = thead.insertRow();
        for (let key of data) {
            let th = document.createElement("th");
            let text = document.createTextNode(key);
            th.appendChild(text);
            row.appendChild(th);
        }
    }

    function generateTable(table, data) {
        for (let element of data) {
            let row = table.insertRow();
            for (key in element) {
                let cell = row.insertCell();
                let text = document.createTextNode(element[key]);
                cell.appendChild(text);
            }
        }
    }

    const table = document.querySelector("table");
    const data = Object.keys(users[0]);
    generateTableHead(table, data);
    generateTable(table, users);
}
users();
<table></table>

Since fetch is asynchronous, you need to process the data only once fetch receives it

This should give you an idea

async function getUsers() {
    let url = '../assets/names.json';
    try {
        let res = await fetch(url);
        return res.json();
    } catch (error) {
        console.log(error);
    }
}
async function fakeGetUsers() {
    // fake delay
    await new Promise(res => setTimeout(res, 1000));
    // simulate return res.json();
    return [{name:"Monte Falco",height:1658,place:"Parco Foreste Casentinesi"}, {name:"Monte Falterona",height:1654,place:"Parco Foreste Casentinesi"}, {name:"Poggio Scali",height:1520,place:"Parco Foreste Casentinesi"}, {name:"Pratomagno",height:1592,place:"Parco Foreste Casentinesi"}, {name:"Monte Amiata",height:1738,place:"Siena"}];
}
async function users() {
    const users = await fakeGetUsers();
    // here you can use the data
    function generateTableHead(table, data) {
        let thead = table.createTHead();
        let row = thead.insertRow();
        for (let key of data) {
            let th = document.createElement("th");
            let text = document.createTextNode(key);
            th.appendChild(text);
            row.appendChild(th);
        }
    }

    function generateTable(table, data) {
        for (let element of data) {
            let row = table.insertRow();
            for (key in element) {
                let cell = row.insertCell();
                let text = document.createTextNode(element[key]);
                cell.appendChild(text);
            }
        }
    }

    const table = document.querySelector("table");
    const data = Object.keys(users[0]);
    generateTableHead(table, data);
    generateTable(table, users);
}
users();
<table></table>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文