JSON HTML

JSON 非常易于转译为 JavaScript。

JavaScript 可用于在网页中生成 HTML。

HTML 表格

使用作为 JSON 接收到的数据来生成表格:

实例

  1. obj = { "table":"customers", "limit":20 };
  2. dbParam = JSON.stringify(obj);
  3. xmlhttp = new XMLHttpRequest();
  4. xmlhttp.onreadystatechange = function() {
  5. if (this.readyState == 4 && this.status == 200) {
  6. myObj = JSON.parse(this.responseText);
  7. txt += "<table border='1'>"
  8. for (x in myObj) {
  9. txt += "<tr><td>" + myObj[x].name + "</td></tr>";
  10. }
  11. txt += "</table>"
  12. document.getElementById("demo").innerHTML = txt;
  13. }
  14. }
  15. xmlhttp.open("POST", "json_demo_db_post.php", true);
  16. xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  17. xmlhttp.send("x=" + dbParam);

动态 HTML 表格

使 HTML 表格基于下拉列表的值:选择一个选项: Customers Products Suppliers

实例

  1. <select id="myselect" onchange="change_myselect(this.value)">
  2. <option value="">Choose an option:</option>
  3. <option value="customers">Customers</option>
  4. <option value="products">Products</option>
  5. <option value="suppliers">Suppliers</option>
  6. </select>
  7.  
  8. <script>
  9. function change_myselect(sel) {
  10. var obj, dbParam, xmlhttp, myObj, x, txt = "";
  11. obj = { "table":sel, "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. }
  29. </script>

HTML 下拉列表

用接收到的 JSON 数据来生成 HTML 下拉列表:

实例

  1. obj = { "table":"customers", "limit":20 };
  2. dbParam = JSON.stringify(obj);
  3. xmlhttp = new XMLHttpRequest();
  4. xmlhttp.onreadystatechange = function() {
  5. if (this.readyState == 4 && this.status == 200) {
  6. myObj = JSON.parse(this.responseText);
  7. txt += "<select>"
  8. for (x in myObj) {
  9. txt += "<option>" + myObj[x].name;
  10. }
  11. txt += "</select>"
  12. document.getElementById("demo").innerHTML = txt;
  13. }
  14. }
  15. xmlhttp.open("POST", "json_demo_db_post.php", true);
  16. xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  17. xmlhttp.send("x=" + dbParam);