生成基于 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 += "<select>"
  18. for (x in myObj) {
  19. txt += "<option>" + myObj[x].name;
  20. }
  21. txt += "</select>"
  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>