生成基于 JSON 数据的 HTML 表格

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h2>做一个基于 JSON 数据的表格。</h2>
  6.  
  7. <p id="demo"></p>
  8.  
  9. <script>
  10. var obj, dbParam, xmlhttp, myObj, x, txt = "";
  11. obj = { table: "customers", limit: 20 };
  12. dbParam = JSON.stringify(obj);
  13. xmlhttp = new XMLHttpRequest();
  14. xmlhttp.onreadystatechange = function() {
  15. if (this.readyState == 4 && this.status == 200) {
  16. myObj = JSON.parse(this.responseText);
  17. txt += "<table border='1'>"
  18. for (x in myObj) {
  19. txt += "<tr><td>" + myObj[x].name + "</td></tr>";
  20. }
  21. txt += "</table>"
  22. document.getElementById("demo").innerHTML = txt;
  23. }
  24. };
  25. xmlhttp.open("POST", "json_demo_db_post.php", true);
  26. xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  27. xmlhttp.send("x=" + dbParam);
  28. </script>
  29.  
  30. </body>
  31. </html>