利用ajax进行前后端交互的简单例子
不多说,上代码:
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>查询所有学生的信息</title>
<link rel="stylesheet" href="css/common.css" />
<script type="text/javascript" src="js/jquery.min.js" ></script>
<style>
body{
background-color: #eee;
}
.main{
width: 800px;
margin: 20px auto;
background-color: #fff;
min-height: 400px;
padding: 10px;
}
.main .toolbar{
margin: 10px 0px;
}
.main .content{
width: 200px;
}
.main .content .empty{
text-align: center;
padding: 4px;
display: block;
border: 0px solid #888;
border-width: 0px 1px 1px 1px;
}
.main .table .c1{
width: 80px;
}
.main .table .c2{
width: 120px;
}
</style>
</head>
<body>
<div class="main">
<div class="toolbar">
<button onclick="query()">查询</button>
</div>
<div class="content">
<table class="table">
<thead>
<th class="c1">学号</th>
<th class="c2">姓名</th>
</thead>
<tbody>
</tbody>
</table>
<div class="empty">
没有数据
</div>
</div>
</div>
</body>
<script>
function query() {
$.ajax({
type:"GET",
url:"queryAll",
dataType:"json",
success:function (resp) {
showResult(resp);
}
})
}
function showResult(result) {
var target = $(".main .content tbody");
target.html("");
for (var row of result){
var str ="<tr>"
+"<td>"+row.no+"</td>"
+"<td>"+row.name+"</td>"
+"</tr>";
target.append(str);
}
if (result.length>0){
$(".main .content .empty").hide();
}else {
$(".main .content .empty").show();
}
}
</script>
</html>
后端部分(servlet)
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import db.StudentDB;
import model.Student;
/**
* Servlet implementation class QueryAllServlet
*/
@WebServlet("/queryAll")
public class QueryAllServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
List<Student> list = StudentDB.queryAll();
JSONArray array = new JSONArray(list);
writer.write(array.toString(2));
}
}
最初没有数据的时候:
点击查询以后: