JSON 可以很容易地转换为 JavaScript。
JavaScript 可用于在网页中制作 HTML。
使用以 JSON 形式接收的数据创建一个 HTML 表:
const dbParam = JSON.stringify({table:"customers",limit:20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
myObj = JSON.parse(this.responseText);
let text = "<table border='1'>"
for (let x in myObj) {
text += "<tr><td>" + myObj[x].name + "</td></tr>";
}
text += "</table>"
document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_html_table.html");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
亲自试一试 »
根据下拉菜单的值制作 HTML 表格:
<select id="myselect" onchange="change_myselect(this.value)">
<option value="">Choose an option:</option>
<option value="customers">Customers</option>
<option value="products">Products</option>
<option value="suppliers">Suppliers</option>
</select>
<script>
function change_myselect(sel) {
const dbParam = JSON.stringify({table:sel,limit:20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
let text = "<table border='1'>"
for (let x in myObj) {
text += "<tr><td>" + myObj[x].name + "</td></tr>";
}
text += "</table>"
document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_html_table.html");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
</script>
亲自试一试 »
使用以 JSON 形式接收的数据创建一个 HTML 下拉列表:
const dbParam = JSON.stringify({table:"customers",limit:20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
let text = "<select>"
for (let x in myObj) {
text += "<option>" + myObj[x].name + "</option>";
}
text += "</select>"
document.getElementById("demo").innerHTML = text;
}
}
xmlhttp.open("POST", "json_demo_html_table.html", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
亲自试一试 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!