一键查询用户信息表
query.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>query</title>
<script src="/static/js/common.js"></script>
<script src="/static/js/jquery-3.3.1.min.js"></script>
<script src="/static/js/query.js"></script>
</head>
<body>
<button id="query">查询</button>
</body>
</html>
query.js
$(function () {
$("#query").click(function () {
// console.log();
let xhr = Xhr();
xhr.open("get", "/qus", true);
xhr.onreadystatechange = function () {
if (this.status === 200 && this.readyState === XMLHttpRequest.DONE) {
// 如果没有table标签,则创建
if ($("table").length == 0) {
let $table = $("<table></table>");
$("body").append($table);
// 添加表头
let $thead = $("<tr><th>id</th><th>name</th><th>nick</th></tr>");
$("table").append($thead);
// 接收数据,添加表内容
let arr = JSON.parse(this.responseText);
arr.forEach(function (e) {
let $tbody = $("<tr>" +
"<td>" + e.id + "</td>" +
"<td>" + e.username + "</td>" +
"<td>" + e.nickname + "</td>" +
"</tr>");
$("table").append($tbody);
});
// 设置表格样式
$("table").attr("style",
"border: 2px solid #aaa; " +
"width:300px; height:200px; " +
"border-collapse:collapse;");
$("td").attr("style", "border: 1px solid #aaa;");
$("th").attr("style", "border: 1px solid #aaa;");
}
}
};
xhr.send(null);
});
});
复选框加载
query.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>query</title>
<script src="/static/js/common.js"></script>
<script src="/static/js/jquery-1.11.3.js"></script>
<script src="/static/js/query.js"></script>
</head>
<body>
<div><span>省份</span><span id="pres"></span>
</div>
<div><span>城市</span><span id="cres"></span>
</div>
</body>
</html>
query.js
function loadProv() {
$.ajax(
{
url: "/qps",
type: "get",
dataType: "json",
async: true,
success: function (data) {
let select = $("<select></select>");
data.forEach(function (e) {
let option = $("<option value='" + e.id + "'>" + e.pname + "</option>");
if (e.id === 1) { //默认选中第一项
option.attr("selected", true);
}
option.attr("value", e.id);
select.append(option);
});
$("#pres").html(select);
// 省份加载完毕后,加载城市
loadCity();
}
}
);
}
function loadCity() {
// 获取被选中的省份id,加载到城市复选框中
let pid = $("#pres").find("option:selected").attr("value"); //相当于 $("#pres select").val()
$.ajax(
{
url: "/qcs",
type: "get",
data: {
pid: pid,
},
dataType: "json",
async: true,
success: function (data) {
let select = $("<select></select>");
data.forEach(function (e) {
let option = $("<option value=''>" + e.cname + "</option>");
if (e.id === 1) { //默认选中第一项
option.attr("selected", true);
}
option.attr("value", e.id);
select.append(option);
});
$("#cres").html(select);
}
}
);
}
$(function () {
// 先加载省份
loadProv();
// 监听省份复选框改变
$("#pres").change(loadCity);
});