简体   繁体   English

如何使用JavaScript在数据表中显示JSON数据-PHP代码有效但不确定如何转换为JavaScript

[英]How to display JSON data in a datatable using JavaScript - PHP code working but not sure how to convert to JavaScript

JSON Data not displaying as a header with column titles ColTitle, row for "Beginning Balance" and then row with ColData. JSON数据未显示为带有标题为ColTitle的标题,为“ Beginning Balance”的行,然后为ColData的行。

PHP code is working fine but its a new JavaScript based app I am working on. PHP代码运行正常,但是我正在开发一个基于JavaScript的新应用。

This is the JavaScript code where I tried to get the table to appear 这是我试图使表格出现的JavaScript代码

Mycontacts is actually a live JSON response but for the purpose of testing I put it on here. Mycontacts实际上是一个实时JSON响应,但是出于测试目的,我将其放在此处。

<script type="text/javascript">
var myContacts = [
{
  "Header": {
    "Time": "2019-05-10T10:38:08-07:00",
    "ReportName": "GeneralLedger",
    "ReportBasis": "Accrual",
    "StartPeriod": "2019-02-01",
    "EndPeriod": "2019-02-01",
    "Currency": "GBP",
    "Option": [
      {
        "Name": "NoReportData",
        "Value": "false"
      }
    ]
  },
  "Columns": {
    "Column": [
      {
        "ColTitle": "Date",
        "ColType": "Date",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "tx_date"
          }
        ]
      },
      {
        "ColTitle": "Transaction Type",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "txn_type"
          }
        ]
      },
      {
        "ColTitle": "No.",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "doc_num"
          }
        ]
      },
      {
        "ColTitle": "Name",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "name"
          }
        ]
      },
      {
        "ColTitle": "Customer",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "cust_name"
          }
        ]
      },
      {
        "ColTitle": "Supplier",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "vend_name"
          }
        ]
      },
      {
        "ColTitle": "Employee",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "emp_name"
          }
        ]
      },
      {
        "ColTitle": "Class",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "klass_name"
          }
        ]
      },
      {
        "ColTitle": "Product/Service",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "item_name"
          }
        ]
      },
      {
        "ColTitle": "Memo/Description",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "memo"
          }
        ]
      },
      {
        "ColTitle": "Account",
        "ColType": "String",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "account_name"
          }
        ]
      },
      {
        "ColTitle": "Debit",
        "ColType": "Money",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "debt_home_amt"
          }
        ]
      },
      {
        "ColTitle": "Credit",
        "ColType": "Money",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "credit_home_amt"
          }
        ]
      },
      {
        "ColTitle": "Amount",
        "ColType": "Money",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "subt_nat_home_amount"
          }
        ]
      }
    ]
  },
  "Rows": {
    "Row": [
      {
        "Header": {
          "ColData": [
            {
              "value": "1000 Bootcamp AMEX Acc",
              "id": "134"
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            }
          ]
        },
        "Rows": {
          "Row": [
            {
              "ColData": [
                {
                  "value": "Beginning Balance"
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                },
                {
                  "value": ""
                }
              ],
              "type": "Data"
            }
          ]
        },
        "Summary": {
          "ColData": [
            {
              "value": "Total for 1000 Bootcamp AMEX Acc"
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            },
            {
              "value": ""
            }
          ]
        },
        "type": "Section"
      },
      }
    ]
  }

    ];

function generateDynamicTable(){

        var noOfContacts = myContacts.length;

        if(noOfContacts>0){


            // CREATE DYNAMIC TABLE.
            var table = document.createElement("table");
            table.style.width = '50%';
            table.setAttribute('border', '1');
            table.setAttribute('cellspacing', '0');
            table.setAttribute('cellpadding', '5');

            // retrieve column header ('Name', 'Email', and 'Mobile')

            var col = []; // define an empty array
            for (var i = 0; i < noOfContacts; i++) {
                for (var key in myContacts[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // CREATE TABLE HEAD .
            var tHead = document.createElement("thead");    


            // CREATE ROW FOR TABLE HEAD .
            var hRow = document.createElement("tr");

            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < col.length; i++) {
                    var th = document.createElement("th");
                    th.innerHTML = col[i];
                    hRow.appendChild(th);
            }
            tHead.appendChild(hRow);
            table.appendChild(tHead);

            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");    

            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < noOfContacts; i++) {

                    var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD .


                    for (var j = 0; j < col.length; j++) {
                        var td = document.createElement("td");
                        td.innerHTML = myContacts[i][col[j]];
                        bRow.appendChild(td);
                    }
                    tBody.appendChild(bRow)

            }
            table.appendChild(tBody);   


            // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
            var divContainer = document.getElementById("myContacts");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);

        }   
    }

</script>

So in the above example I expected the first row of the table to have column headings, then a row for ColData - "value": "1000 Bootcamp AMEX Acc", then a row for ColData - "value": "Beginning Balance", then finally a row for ColData - "value": "Total for 1000 Bootcamp AMEX Acc". 因此,在上面的示例中,我希望表的第一行具有列标题,然后是ColData的一行-“ value”:“ 1000 Bootcamp AMEX Acc”,然后是ColData的一行-“ value”:“ Beginning Balance”,然后最后一行显示ColData-“ value”:“总共1000 Bootcamp AMEX Acc”。

This is just a sample - my live data is much larger than this so needed a loop for each of the Columns, Rows, Rows, Summary. 这只是一个示例-我的实时数据远大于此,因此需要为“列”,“行”,“行”,“摘要”中的每个循环。

The below PHP coding seemed to work fine when using an SDK 使用SDK时,以下PHP编码似乎可以正常工作

echo "Report Name - " . $report['Header']['ReportName'];
            echo "<br>";
            echo "For Date: " . $report['Header']['DateMacro'] . " (".$report['Header']['StartPeriod']." - ".$report['Header']['EndPeriod'].")";
            echo "<br>";            
            echo "Currency: " . $report['Header']['Currency'];
            echo "<br>";
            echo "<hr>";
            echo '<table><thead>';

            $NumberColumns = array();
            echo '<th></th>';
            // echo '<th>Account Name</th>';
            $NumberColumns[]= ''; // get a foreach for number of cols if we need it
            foreach ($report['Columns']['Column'] as $HeadKey => $columns) {
                $NumberColumns[]= '';
                echo '<th>';
                echo $columns['ColTitle'];
                if($columns['ColTitle'] == 'Credit') {
                    $CreditKey = $HeadKey;
                }
                echo '</th>';
            }
            echo '</thead><tbody>';


            foreach($report['Rows']['Row'] as $MainRow) {
                echo '<tr style="background-color:lightgrey">';
                echo '<td><h3>' . $MainRow['Header']['ColData']['0']['value'] . '</h3></td>'; // SPLITTER ROW - SUMMARY
                foreach ($MainRow['Summary']['ColData'] as $MainRowData) {
                    if ($counter++ == 0) continue;
                    echo '<td>' . $MainRowData['value'] . '</td>';
                }
                unset($counter);
                echo '</tr>';
                foreach($MainRow['Rows']['Row'] as $DetailRow) {
                    echo '<td></td>';
                    echo '</td>';
                    foreach($DetailRow['ColData'] as $DetailKey => $CellDetail) {
                        $CellContents = $CellDetail['value'];
                        if($DetailKey == $CreditKey) {
                            $CellContents = abs($CellDetail['value']) * -1;
                        }
                        echo '<td>' . $CellContents . '</td>';
                    }
                    echo '</tr>';
                }
            } // Main ROW
            echo '</tbody></table>';

  1. Some brackets got mixed up or were missing in myContacts Rows object. myContacts Rows对象中的某些括号混淆或丢失。 See comments in code sample. 请参阅代码示例中的注释。

  2. The div with the id "myContacts" where you want to render your table, was not defined in your html markup. 您想在其中呈现表格的ID为“ myContacts”的div在html标记中未定义。 Here is the part where you call it: 这是您称之为的部分:

var divContainer = document.getElementById("myContacts");
  1. you defined your rendering function but forgot to call it initially: 您定义了渲染功能,但最初忘记了调用它:
generateDynamicTable() // TODO: call was missing at the end of your script

ADDITIONAL: So you can use something like this for debugging purpose to get the right value :) 另外:因此,您可以使用类似的方法进行调试,以获得正确的值:)

td.innerHTML = myContacts[i][col[j]]; // instead of this
td.innerHTML = JSON.stringify(myContacts[ i ][ col[ j ] ]); // use this

Hope I could help :) 希望我能帮助:)

Fiddle: https://jsfiddle.net/0xsf8qmg/ 小提琴: https : //jsfiddle.net/0xsf8qmg/

Here the Code: 这里的代码:

 var myContacts = [ { "Header": { "Time": "2019-05-10T10:38:08-07:00", "ReportName": "GeneralLedger", "ReportBasis": "Accrual", "StartPeriod": "2019-02-01", "EndPeriod": "2019-02-01", "Currency": "GBP", "Option": [ { "Name": "NoReportData", "Value": "false" } ] }, "Columns": { "Column": [ { "ColTitle": "Date", "ColType": "Date", "MetaData": [ { "Name": "ColKey", "Value": "tx_date" } ] }, { "ColTitle": "Transaction Type", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "txn_type" } ] }, { "ColTitle": "No.", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "doc_num" } ] }, { "ColTitle": "Name", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "name" } ] }, { "ColTitle": "Customer", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "cust_name" } ] }, { "ColTitle": "Supplier", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "vend_name" } ] }, { "ColTitle": "Employee", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "emp_name" } ] }, { "ColTitle": "Class", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "klass_name" } ] }, { "ColTitle": "Product/Service", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "item_name" } ] }, { "ColTitle": "Memo/Description", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "memo" } ] }, { "ColTitle": "Account", "ColType": "String", "MetaData": [ { "Name": "ColKey", "Value": "account_name" } ] }, { "ColTitle": "Debit", "ColType": "Money", "MetaData": [ { "Name": "ColKey", "Value": "debt_home_amt" } ] }, { "ColTitle": "Credit", "ColType": "Money", "MetaData": [ { "Name": "ColKey", "Value": "credit_home_amt" } ] }, { "ColTitle": "Amount", "ColType": "Money", "MetaData": [ { "Name": "ColKey", "Value": "subt_nat_home_amount" } ] } ] }, "Rows": { "Row": [ { "Header": { "ColData": [ { "value": "1000 Bootcamp AMEX Acc", "id": "134" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" } ] }, "Rows": { "Row": [ { "ColData": [ { "value": "Beginning Balance" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" } ], "type": "Data" } ] }, "Summary": { "ColData": [ { "value": "Total for 1000 Bootcamp AMEX Acc" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" }, { "value": "" } ] }, "type": "Section" }, ] // TODO: this one was missing } // ] TODO: this one is accidentally } ]; function generateDynamicTable(){ var noOfContacts = myContacts.length; if(noOfContacts>0){ // CREATE DYNAMIC TABLE. var table = document.createElement("table"); table.style.width = '50%'; table.setAttribute('border', '1'); table.setAttribute('cellspacing', '0'); table.setAttribute('cellpadding', '5'); // retrieve column header ('Name', 'Email', and 'Mobile') var col = []; // define an empty array for (var i = 0; i < noOfContacts; i++) { for (var key in myContacts[i]) { if (col.indexOf(key) === -1) { col.push(key); } } } // CREATE TABLE HEAD . var tHead = document.createElement("thead"); // CREATE ROW FOR TABLE HEAD . var hRow = document.createElement("tr"); // ADD COLUMN HEADER TO ROW OF TABLE HEAD. for (var i = 0; i < col.length; i++) { var th = document.createElement("th"); th.innerHTML = col[i]; hRow.appendChild(th); } tHead.appendChild(hRow); table.appendChild(tHead); // CREATE TABLE BODY . var tBody = document.createElement("tbody"); // ADD COLUMN HEADER TO ROW OF TABLE HEAD. for (var i = 0; i < noOfContacts; i++) { var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD . for (var j = 0; j < col.length; j++) { var td = document.createElement("td"); // td.innerHTML = JSON.stringify(myContacts[ i ][ col[ j ] ]); // TODO: for debugging purpose instead of the following line td.innerHTML = myContacts[i][col[j]]; bRow.appendChild(td); } tBody.appendChild(bRow) } table.appendChild(tBody); // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER. var divContainer = document.getElementById("myContacts"); divContainer.innerHTML = ""; divContainer.appendChild(table); } } generateDynamicTable() // TODO: call was missing 
 <div id="myContacts"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM