簡體   English   中英

如何將JSON數據添加到HTML表

[英]How to add JSON data to a HTML table

目前,我正在獲取需要添加到HTML表中的數據。

我已經嘗試了一些方法,但是一旦頁面加載后就無法動態添加數據。

我想使用Javascript或jQuery添加它

這是HTML結構:

<div>
    <table cellspacing="0" cellpadding="0">
        <thead>
          <tr>
            <th scope="col"><span>Email</span></th>
            <th><span>Last Name</span></th>
            <th><span>First Name</span></th>
            <th><span>Role</span></th>
            <th><span>Cell Phone User</span></th>
          </tr>
        </thead>
           <tbody>
              <tr>
                 <td scope="row" data-label="Email"></td>
                 <td data-label="Last Name"></td>
                 <td data-label="First Name"></td>
                 <td data-label="Role"></td>
                 <td data-label="Cell Phone User"></td>
               </tr>
           </tbody> 
    </table>
</div>

這是獲取數據后的外觀示例:

[{
    "id": 1,
    "email": "janedoe@example.com",
    "familyName": "Doe",
    "givenName": "Jane",
    "role": "admin",
    "smsUser": true
  },
  {
    "id": 2,
    "email": "johndoe@example.com",
    "familyName": "Doe",
    "givenName": "John",
    "role": "standard",
    "smsUser": false
  }]

到目前為止,這是我嘗試過的:

這是我的事件監聽器,用於在頁面加載后加載數據:


window.path = "http://localhost:3000/users";

// getUsers function plus any additional functions go here ...
const getUsers = options => {
  let url = new URL(window.path);
  if (options) {
    url.search = new URLSearchParams(options)
  }
  return Promise.resolve(fetch(url))
}

document.addEventListener('DOMContentLoaded', () => {

 /* SELECT DOM ELEMENTS*/ 
let table = document.querySelector('tbody');

let promise = getUsers({page=2, role:'admin'})

.then(data => {

var html = '<table>';
for( var j in data[0] ) {
    html += '<th>' + j + '</th>';
 }
     html += '</tr>';

     for( var i = 0; i < data.length; i++) {
      html += '<tr>';
      for( var j in data[i] ) {
        html += '<td>' + data[i][j] + '</td>';
      }
     }
     html += '</table>';
     table.appendChild(html)

    return table;
  })
.catch(err => {
    console.log('Error fetching from /users', err);
    return null
  })

})



任何幫助表示贊賞。

第一個問題是線

let promise = getUsers({page=2, role:'admin'})

應該

let promise = getUsers({page:2, role:'admin'})

其次, appendChild不使用字符串,而是使用DOM元素。 對於這種情況,請改用innerHTML。

第三,您正在使用querySelect查找'<tbody>'元素,因此從'<tr>'而不是'<table>'開始構建內部html標簽。

 const getUsers = async options => ([ { id: 1, email: "janedoe@example.com", familyName: "Doe", givenName: "Jane", role: "admin", smsUser: true }, { id: 2, email: "johndoe@example.com", familyName: "Doe", givenName: "John", role: "standard", smsUser: false } ]); document.addEventListener('DOMContentLoaded', async () => { const table = document.querySelector('tbody'); const users = await getUsers({ page:2, role:'admin' }); const userToTableRow = user => [ { attrs: 'scope="row" data-label="Email"', propName: 'email'}, { attrs: 'data-label="Last Name"', propName: 'familyName'}, { attrs: 'data-label="First Name"', propName: 'givenName'}, { attrs: 'data-label="Role Name"', propName: 'role'}, { attrs: 'data-label="Cell Phone User"', propName: 'smsUser'}, ].map(mapper => ( `<td ${mapper.attrs}>${user[mapper.propName]}</td>` )).join(''); const html = users.map(user => `<tr>${userToTableRow(user)}</tr>` ).join(''); table.innerHTML = html; }); 
 <div> <table cellspacing="0" cellpadding="0"> <thead> <tr> <th scope="col"><span>Email</span></th> <th><span>Last Name</span></th> <th><span>First Name</span></th> <th><span>Role</span></th> <th><span>Cell Phone User</span></th> </tr> </thead> <tbody> </tbody> </table> </div> 

編輯:我喜歡上面的第一個實現中的異步/等待。 async只是強制函數將返回值包裝在Promise中的簡便方法。 await只是一種新的語言方式,無需使用.then((res) => {...})即可解決內聯的.then((res) => {...}) await只能在async函數中使用。

解決評論中的問題。 我提交了以下替代解決方案:

  • 不使用asyncawait
  • 模擬fetch而不是getusers
  • 使用document.createElement()和appendChild,而不只是設置innerHTML內容。

 const getUsersUrl = 'http://localhost:3000/users'; function mockFetch(url) { const stubbedResponse = JSON.stringify([ { id: 1, email: "janedoe@example.com", familyName: "Doe", givenName: "Jane", role: "admin", smsUser: true }, { id: 2, email: "johndoe@example.com", familyName: "Doe", givenName: "John", role: "standard", smsUser: false } ]); return Promise.resolve({ json() { return Promise.resolve(JSON.parse(stubbedResponse)); } }); } const getUsers = options => { let url = new URL(getUsersUrl); if (options) { url.search = new URLSearchParams(options) } return mockFetch(url); } const userToTableRow = user => { const tr = document.createElement('tr'); [ { attrs: { scope: 'row', 'data-label': 'Email' }, propName: 'email' }, { attrs: { 'data-label': 'Last Name' }, propName: 'familyName' }, { attrs: { 'data-label': 'First Name' }, propName: 'givenName' }, { attrs: { 'data-label': 'Role Name' }, propName: 'role' }, { attrs: { 'data-label': 'Cell Phone User' }, propName: 'smsUser' }, ].map(mapper => { const td = document.createElement('td'); for (const [attrName, attrValue] of Object.entries(mapper.attrs)) { td.setAttribute(attrName, attrValue); } td.appendChild(document.createTextNode(user[mapper.propName])); return td; }).forEach(td => { tr.appendChild(td); }); return tr; } document.addEventListener('DOMContentLoaded', () => { const table = document.querySelector('tbody'); getUsers({ page:2, role:'admin' }) .then(response => response.json()) .then(users => { users .map(user => userToTableRow(user)) .forEach(tr => { table.appendChild(tr); }); }); }); 
 <div> <table cellspacing="0" cellpadding="0"> <thead> <tr> <th scope="col"><span>Email</span></th> <th><span>Last Name</span></th> <th><span>First Name</span></th> <th><span>Role</span></th> <th><span>Cell Phone User</span></th> </tr> </thead> <tbody> </tbody> </table> </div> 

使用jQuery,做到這一點非常簡單。

以此代碼段為例,它利用jQuery DataTables庫。

 $(document).ready(function() { $('#example').DataTable( { ajax: { url: "https://reqres.in/api/users", dataSrc: "data" }, columns: [ { "data": "id" }, { "data": "first_name" }, { "data": "last_name" } ] } ); } ); 
 <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" /> <table id="example" class="display" style="width:100%"> <thead> <tr> <th>Id</th> <th>First Name </th> <th>Last Name</th> </tr> </thead> </table> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> 

它還提供了各種配置和集成,我相信您會發現它會有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM