带有JSON数据的动态Javascript表


Dynamic Javascript table with JSON data

我正试图使用从PHP脚本中提取的Javascript和JSON数据来创建和填充一个动态表。我遇到的问题是,创建了第一行(标题),JSON对象中的键被放在正确的位置,但我无法创建第二行,其中包含与这些键相关的值(或者它没有显示)。这是我的JS代码:

var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
    var Json = JSON.parse(this.responseText);
    for (value in Json.prods[0]){
        alert(value);
    }
    var newTable = document.createElement('table');
    //Create first row
    var tableRowFirst = document.createElement('tr');
    for (key in Json.prods[0]) {
        //create new heading
        var keys = document.createElement('th');
        // append Heading to table
        tableRowFirst.appendChild(keys);
        //set new heading text content to json information
        keys.textContent = key;
    };
    //Create rows
    var tableBody = document.createElement('tbody');
    var tableRow = document.createElement('tr');
    tableBody.appendChild(tableRow);
    for (key in Json.prods[0]) {
        //create new cell
        var values = document.createElement('td');
        // append cell to row
        tableRow.appendChild(values);
        //set new content text content to json information
        values.textContent = Json.prods[0].key;
    };
    //Append table to DOM
    document.body.appendChild(newTable);
    //Append rows to new table
    newTable.appendChild(tableRowFirst);
    newTable.appendChild(tableBody);
};
oReq.open("get", "../php/getalltag.php", true);
oReq.send();

有人能帮我吗?

我猜您设置textContent的方式不对,因为您试图获取名为key的属性,但key实际上是一个存储真实属性名称的局部变量。

 for (key in Json.prods[0]) {
        ...
        //set new content text content to json information
        values.textContent = Json.prods[0].key;
    };

这应该很好:

values.textContent = Json.prods[0][key];

您应该将tableBody.appendChild(tableRow);放在行for循环之后。

当执行newTable.appendChild(tableBody);时,tableBody不会从新行中更新,因为它在循环之前已更新。因此,必须在tableRow具有所有必需的值/行之后更新tableBody

因此,下面的代码

//Create rows
    var tableBody = document.createElement('tbody');
    var tableRow = document.createElement('tr');
    tableBody.appendChild(tableRow);
    for (key in Json.prods[0]) {
        //create new cell
        var values = document.createElement('td');
        // append cell to row
        tableRow.appendChild(values);
        //set new content text content to json information
        values.textContent = Json.prods[0].key;
    };

成为

//Create rows
    var tableBody = document.createElement('tbody');
    var tableRow = document.createElement('tr');
    for (key in Json.prods[0]) {
        //create new cell
        var values = document.createElement('td');
        // append cell to row
        tableRow.appendChild(values);
        //set new content text content to json information
        values.textContent = Json.prods[0].key;
    };
    tableBody.appendChild(tableRow); // MOVED HERE