- 前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取信息列表</title>
</head>
<body>
<script>
window.onload = function(){
document.getElementById("btn").onclick = function(){
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function(){
if(this.readyState == 4){
if (this.status == 200) {
// document.getElementById("stutbody").innerHTML = this.responseText
// 将json格式的字符串转换成json对象
var stuList = JSON.parse(this.responseText)
var html = ""
for (let i = 0; i < stuList.length; i++) {
const stu = stuList[i];
html += "<tr>"
html += " <td>"+stu.name+"</td>"
html += " <td>"+stu.age+"</td>"
html += " <td>"+stu.address+"</td>"
html += "</tr>"
}
document.getElementById("stutbody").innerHTML = html
}else{
alert(this.status)
}
}
}
xhr.open("GET","/URL?t="+Math.random(),true)
xhr.send()
}
}
</script>
<input type="button" value="显示信息" id="btn">
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>住址</th>
</tr>
<tbody id="stutbody">
<!-- <tr>
<td>zhangsan</td>
<td>20</td>
<td>sh</td>
</tr> -->
</tbody>
</table>
</body>
</html>
- 后端代码
// 后端代码
声明HttpServletResponse
// 连接数据库
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 循环数据
out.print();
// 把数据给前端,然后把页面展示让前端展示
// 可以采用json格式或者xml格式
<!-- String jsonstr = "[{
\"name\":\"zhangsan\",
\"age\":20,
\"address\":\"shan\"
},{
\"name\":\"zhangsan\",
\"age\":20,
\"address\":\"shan\"
}]"; -->
// 动态拼接json字符串
StringBuilder json = new StringBuilder();
json.append("[");
json.append("{\"name\":\"");
json.append(name);
json.append("\",\"age\":");
json.append(age);
json.append(",\"address\":\"");
json.append(address);
json.append("\"},");
json.substring(0,json.length()-1+"]");
out.print(jsonstr)
标签:stu,--,AJAX,xhr,json,html,格式,append From: https://www.cnblogs.com/hyy-0/p/17591798.html