JSON HTML
JSON 非常易于转译为 JavaScript。
JavaScript 可用于在网页中生成 HTML。
HTML 表格
使用作为 JSON 接收到的数据来生成表格:
<!DOCTYPE html><html><body><h2>做一个基于 JSON 数据的表格。</h2><p id="demo"><script>var obj, dbParam, xmlhttp, myObj, x, txt = "";obj = { table: "customers", limit: 20 };dbParam = JSON.stringify(obj);xmlhttp = new XMLHttpRequest();xmlhttp.onreadystatechange = function() {if (this.readyState == 4 && this.status == 200) {myObj = JSON.parse(this.responseText);txt += "<table border='1'>"for (x in myObj) {txt += "<tr><td>" + myObj[x].name + "</td></tr>";}txt += "</table>"document.getElementById("demo").innerHTML = txt;}};xmlhttp.open("POST", "json_demo_db_post.php", true);xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xmlhttp.send("x=" + dbParam);</script></body></html>
动态 HTML 表格
使 HTML 表格基于下拉列表的值:选择一个选项
<!DOCTYPE html><html><body><h2>做一个基于下拉列表值的表格。</h2><select id="myselect" onchange="change_myselect(this.value)"><option value="">选择一个选项:<option value="customers">客户<option value="products">商品<option value="suppliers">供应商</select><p id="demo"><script>function change_myselect(sel) {var obj, dbParam, xmlhttp, myObj, x, txt = "";obj = { table: sel, limit: 20 };dbParam = JSON.stringify(obj);xmlhttp = new XMLHttpRequest();xmlhttp.onreadystatechange = function() {if (this.readyState == 4 && this.status == 200) {myObj = JSON.parse(this.responseText);txt += "<table border='1'>"for (x in myObj) {txt += "<tr><td>" + myObj[x].name + "</td></tr>";}txt += "</table>"document.getElementById("demo").innerHTML = txt;}};xmlhttp.open("POST", "json_demo_db_post.php", true);xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xmlhttp.send("x=" + dbParam);}</script></body></html>
HTML 下拉列表
用接收到的 JSON 数据来生成 HTML 下拉列表:
<!DOCTYPE html><html><body><h2>做一个基于 JSON 数据的下拉列表。</h2><p id="demo"><script>var obj, dbParam, xmlhttp, myObj, x, txt = "";obj = { table: "customers", limit: 20 };dbParam = JSON.stringify(obj);xmlhttp = new XMLHttpRequest();xmlhttp.onreadystatechange = function() {if (this.readyState == 4 && this.status == 200) {myObj = JSON.parse(this.responseText);txt += "<select>"for (x in myObj) {txt += "<option>" + myObj[x].name;}txt += "</select>"document.getElementById("demo").innerHTML = txt;}};xmlhttp.open("POST", "json_demo_db_post.php", true);xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xmlhttp.send("x=" + dbParam);</script></body></html>