提问者:小点点

使用AJAX JavaScript将数据加载到HTML表中无法工作


我有数据存储在json文件中,像这样:

[
["cell1", "cell2", "cell3"],
["cell4", "cell5", "cell6"]
...
]

我想将json数据转换为html表,因此我创建了以下代码(html结构+从位于同一目录“rows.json”中的专用json数据文件中分别加载数据):

<body>
    <table id="tab">
        <thead>
            <tr>
                <th>column_1</th>
                <th>column_2</th>
                <th>column_3</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

<script type="text/javascript">
        const TabBody = document.querySelector("#tab > tbody") 
        function loadData() {
            const request = new XMLHttpRequest();
            request.open("get", "rows.json");
            request.onload = () => {
                try {
                    const json = JSON.parse(request.responseText);
                    populateTable(json);
                    }  catch (e) {
                        console.warn("error");
                    }   
                };
                
            request.send();
        }
        function populateTable(json){
            
            while(TabBody.firstChild){TabBody.removeChild(TabBody.firstChild);}

            json.forEach((row) => { 
                const tr = document.createElement("tr");

                row.forEach((cell) => {
                    const td = document.createElement("td");
                    td.textContent = cell;
                    tr.appendChild(td);})
                
                TabBody.appendChild(tr);
            })            
        }
    </script>
</body>

代码不工作,表体未加载显示。 也许代码不正确,或者效率不高,有更好的方法来实现它。


共2个答案

匿名用户

您的PopulateTable函数看起来是正确的,我将它复制到一个代码片段中,它工作得很好。

  • 是否从XMLHttpRequest中获得正确的数据?
  • 在哪里调用LoadData函数? 你忘了给它打电话了吗?

null

const data = [
  ["cell1", "cell2", "cell3"],
  ["cell4", "cell5", "cell6"]
]

const TabBody = document.querySelector("#tab > tbody");

function populateTable(json) {

  while (TabBody.firstChild) {
    TabBody.removeChild(TabBody.firstChild);
  }

  json.forEach((row) => {
    const tr = document.createElement("tr");

    row.forEach((cell) => {
      const td = document.createElement("td");
      td.textContent = cell;
      tr.appendChild(td);
    })

    TabBody.appendChild(tr);
  })
}

populateTable(data);
<table id="tab">
  <thead>
    <tr>
      <th>column_1</th>
      <th>column_2</th>
      <th>column_3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

匿名用户

在这种情况下可以使用Tabulator。 您可以在内部加载json数据,它为您提供了许多特性和样式表的能力。

在这里,您可以了解如何从ajax请求插入数据:http://tabulator.info/docs/4.1/data#ajax

如果您想要在表中发出请求并输入响应,可以在从代码中获得响应后执行此操作:

var table = new Tabulator("#example-table", {
                height: '70%', // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
                data: res.json, //assign data to table, json response
                layout: "fitDataFill", //fit columns to width of data
                pagination: "local",
                paginationSize: 10,
                paginationSizeSelector: [5, 10, 15, 20],
                movableColumns: true,
                selectable: true,
                columns: [
                    {
                        formatter: "buttonCross", align: "center", title: "del", headerSort: false, cellClick: function (e, cell) {
                            if (confirm('Are you sure you want to delete this entry?'))
                                cell.getRow().delete();
                            console.log(rowJson = cell.getRow().getData())
                        }
                    },
                    { title: "id", field: "id", sorter: "number" },
                    { title: "Name", field: "name", sorter: 'string' },
                    { title: "phone", field: "phone", sorter: "number" },
                    { title: "email", field: "email", sorter: 'string' },
                    { title: "location", field: "location", sorter: 'string' },
                    { title: "price/night", field: "price", sorter: 'number' },
                    { title: "number of rooms", field: "roomsnumber", sorter: 'number' },
                    { title: "capacity", field: "capacity", sorter: 'number' },
                    { title: "available", field: "available", sorter: 'string' },
                    { title: "start time", field: "startTime", sorter: 'string' },
                    { title: "date", field: "date", sorter: "date", },
                ]
                
            });

它非常容易使用,并且有许多特性。