如何从 JSON 数据创建 html table 结果

how to create html table results from JSON data

我的代码使用 AJAX 和 JSON 在您进行搜索时输出一大块 SQL 数据,我正在尝试将数据分开并显示变成 HTML table。起初它只是 SQL 数据,但我将一些标签放入内部 HTML 行以至少在视觉上将其分开,但是我真的很想能够将每一列放入一个单独的 table 单元格。任何关于如何做到这一点的想法将不胜感激。这是代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="js/jquery-2.2.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <title>AJAX Search Example</title>
    <script>
    function fetch() {
      // (A) GET SEARCH TERM
 
      var data = new FormData();
      data.append('search', document.getElementById("search").value);
      data.append('ajax', 1);

      // (B) AJAX SEARCH REQUEST
      var xhr = new XMLHttpRequest();
    
      // (CHANGE1) USING ONREADYSTATECHNAGE INSTEAD OF ONLOAD
      
    xhr.onreadystatechange =  function (event) {
        // (CHANGE2) we will check if ajax process has completed or not it goes from 1,2,3,4 means end. 

if(this.readyState == 4){

// (CHANGE2) when ready state comes to 4 we then check what response status was it if it is 200 good else error. 

if(this.status == 200){
    // (CHANGE3) MOVED ALL YOUR CODE HERE 

// (CHANGE4) we need to use responseText instead of response because JSON comes as string that is why we are parsing it to be converted into array

var results = JSON.parse(this.responseText);
    //I have added just a measure to check what the out put is you can remove it latter. open dev console to get the result.
    console.log(results);

wrapper = document.getElementById("results");
    if (results.length > 0) {
          wrapper.innerHTML = "";

// (CHANGE5) UPDATED data ref with results 

for (i = 0; i <  results.length; i++) {
            let line = document.createElement("div");
              //it is just as simple to create id only it must start with alphabet not number 

line.id=`res${[i]}`;

//we created span tag to display price and this is what we will change. on that span we will create a data-price attribute which will hold original price and we will run calculations using that number 

//BIG CHANGE
//BIG CHANGE

//since after parsing individual record will be in Js object so we dont need to access them like array  results[i]['item']

//we access them with dot notation results[i].item

line.innerHTML = `Category:${results[i].category} - OEM #:${results[i].oemnumber} - Price:$<span data-price='${results[i].price}'>${results[i].price}</span>
            select discount >>   
            <a href="#70">%70</a>
    <a href="#60">%60</a>
    <a href="#50">%50</a> <a href="#50">100%</a>`; 
            wrapper.appendChild(line);
          }

 // (CHANGE6) We moved event listeners here so any newly added elements will be updated. 

 //get all the links and apply event listener through loop   
 
    var links = document.querySelectorAll('a');
      

      for ( ii = 0; ii <  links.length; ii++) {
         links[ii].addEventListener("click", function(event) {
         
       //capture link value and get number to be converted to percentage  
       
       var percentage = event.target.innerText.match(/\d+/)[0]/100;
 
 //capture the data-price which is within same div as anchor link
 
 var pricetarget = event.target.parentElement.querySelector('[data-price]');
 
 //get value of data-price
 
 var actualprice=  pricetarget.dataset.price;
 
 //run math and chnage the value on display
 
 pricetarget.innerHTML=(actualprice*percentage).toFixed(2);
      
      
      });
      }

        } else { wrapper.innerHTML = "No results found"; }

 } else {
 
 //if reponse code is other ethan 200 

alert('INTERNET  DEAD OR AJAX FAILED ');

 }

 }
       

            

      };

// (CHANGE7) We moved open event to end so everything is ready before it fires.

xhr.open('POST', "2-search.php");
      xhr.send(data);
      return false;

 
    };
    </script>
  </head>
  <body>
    <!-- (A) SEARCH FORM -->
    <form ID='myForm' onsubmit="return fetch();">
      <h1>SEARCH FOR CATALYTIC CONVERTER</h1>
      <input type="text" id="search" required/>
      <input type="submit" value="Search"/>
    </form>

    <!-- (B) SEARCH RESULTS -->
    <div id="results"></div>


  </body>
  </html>

这里是我添加标签的地方,至少在视觉上将它分开:“line.innerHTML = `Category:${results[i].category} - OEM #:${results[i].oemnumber } - 价格:$${results[i].price}

我想要做的是将类别、OEM # 和价格分别放在单独的 table 单元格中。感谢您提供的任何帮助。

您可以简单地在 for (i = 0; i < results.len.. 中生成 trs ,就像您已经在为 div 所做的那样。所以,只需使用 += 将每个新的 tr 附加到 tbody 中,然后将其附加到您的 table

演示代码 :

//suppose json look like below :)
var results = [{
  "category": "A",
  "price": 13,
  "oemnumber": "d1A"
}, {
  "category": "B",
  "price": 15,
  "oemnumber": "d1B"
}, {
  "category": "C",
  "price": 12,
  "oemnumber": "d1C"
}]
fetch();

function fetch() {
  /*  var data = new FormData();
   data.append('search', document.getElementById("search").value);
   data.append('ajax', 1);
   var xhr = new XMLHttpRequest();

   // (CHANGE1) USING ONREADYSTATECHNAGE INSTEAD OF ONLOAD

     //some codes/..    
    console.log(results);*/

  wrapper = document.getElementById("results");
  wrapper.innerHTML = "";
  var rows = "";
  if (results.length > 0) {
    for (i = 0; i < results.length; i++) {
      //generate trs
      rows += `<tr id=res${[i]}><td>${results[i].category}</td><td>${results[i].oemnumber}</td><td>$<span data-price='${results[i].price}'>${results[i].price}</span>
            select discount >>   
            <a href="#70">%70</a>
    <a href="#60">%60</a>
    <a href="#50">%50</a> <a href="#50">100%</a></td></tr>`;
    }
    wrapper.innerHTML = `<table class="table">
    <thead><th>Category</th><th>OEM</th><th>Price</th></thead><tbody>${rows}</tbody></table>`;

    //sme other codes,,

  }
};
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<div id="results">
</div>