JSON HTML@TOC
JSON HTML
JSON 可以很容易地转换为 JavaScript。
JavaScript 可用于在网页中制作 HTML。
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.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
动态 HTML 表
根据下拉菜单的值制作 HTML 表:
选择一个选项:
示例
<select id="myselect" onchange="change_myselect(this.value)">
<option value="">选择一个选项:</option>
<option value="customers">客户</option>
<option value="products">产品</option>
<option value="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.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
</script>
HTML 下拉列表
使用 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.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.发送(“x=” + dbParam);
总结
本文介绍了JSON在HTML中的使用,如有问题欢迎私信和评论