当前位置: 首页 > 知识库问答 >
问题:

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

隆长卿
2023-03-14

我有数据存储在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个答案

能文华
2023-03-14

在这种情况下可以使用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", },
                ]
                
            });

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

薛晨
2023-03-14

您的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);
html lang-html prettyprint-override"><table id="tab">
  <thead>
    <tr>
      <th>column_1</th>
      <th>column_2</th>
      <th>column_3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
 类似资料:
  • 我无法将数据加载到表中。我有类,其名称为、等。我想将、插入到TextField上的表播放器中。 我正在执行与下面所示完全相同的操作:http://docs.oracle.com/javase/8/javafx/user-interface-tutorial/table-view.htm#cjagaaee 但我不能让它起作用。有人能帮我吗?

  • 无法通过jupyter笔记本使用pyspark将数据写入hive。 给我下面的错误 Py4JJavaError:调用o99.saveAsTable时发生错误。:org.apache.spark.sql.分析异常:java.lang.运行时异常:java.lang.运行时异常:无法实例化org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreCl

  • 我已经把Kafka和博士后的成绩记录下来了。我使用JDBC接收器连接器将数据从Kafka主题加载到Postgres表。首先,我用“AVRO”值格式创建一个主题和一个主题上方的流。 以下是创建接收器连接器的代码: 然后,我使用命令检查Postgres是否有来自Kafka的数据,它返回以下信息:

  • 其次,是否需要从Graphene DB实例访问csv导入文件,或者这是客户端关心的问题?

  • 问题内容: 我正在尝试通过JQUERY AJAX调用来更新页面加载和选择菜单更改时的高图表。有以[[10,1228800000],[10,1228800000]]格式返回的数据。图表为空白,不对任何数据进行图形处理。 尝试了此处发布的几种解决方案,但没有一个有效。 有什么错误吗?提前致谢。编辑: 最新的代码仍然无法正常工作: 问题答案: 您必须使用文档中描述的系列对象的setData方法。你的情况

  • 创建表之后,你需要填充数据,你可以通过LOAD DATA和INSERT来实现。 数据格式如下: Whistler Gwen bird \N 1997-12-09 \N 列之间使用\t间隔(LOAD DATA默认的列间隔符),\N表示NULL。 加载文件pet.txt中的数据到表pet中,使用以下命令: mysql> LOAD DATA LOCAL I

  • 我刚接触Cassandra Spark,并尝试使用Spark主集群将数据从文件加载到Cassandra表。我遵循以下链接中给出的步骤 http://docs.datastax.com/en/datastax_enterprise/4.7/datastax_enterprise/spark/sparkImportTxtCQL.html 在第8步,数据显示为整数数组,但当我使用相同的命令时,结果显示为

  • 我正在使用hazelcast IMap存储我的应用程序数据。 我面临着一个小问题。 问题说明:- 当我启动spring-boot应用程序时,我正在将数据库表数据加载到hazelcast中。 示例:- 但是当我获取相同的数据时,我得到的顺序不同。 那么有没有办法按照插入的顺序获取数据呢?