目录
基于Ajax+JSon的表格数据浏览【简单版--没连接数据库】
代码:
ajax.js
ch10_4.jsp
student.java
Query.java
运行结果:
点击获取表格后:
基于Ajax+JSon的表格数据浏览【简单版--没连接数据库】
代码:
ajax.js
//声明XMLHttpRequest对象
var httpRequest=null;
//创建XMLHttpRequest对象实例的方法
function createXHR(){
    if(window.XMLHttpRequest){
        httpRequest=new XMLHttpRequest();
    }else if(window.ActiveXObject){
        try{
            httpRequest=new ActiveXObject("Maxml2.XMLHTTP");//IE较新版
        }catch (e){
            try{
                httpRequest=new ActiveXObject("Microsoft.XMLHTTP");//IE较老版
            }catch (e) {
                httpRequest=null;
            }
        }
    }
    if (!httpRequest){
        alert("fail to create httpRequest!");
    }
}
function sendRequest(url,params,method,handler){
    createXHR();
    if (!httpRequest){
        return false;
    }
    httpRequest.onreadystatechange=handler;
    if(method=="GET"){
        httpRequest.open(method,url+'?'+params,true);
        httpRequest.send(null);
    }
    if (method=="POST"){
        httpRequest.open(method,url,true);
        httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        httpRequest.send(params);
    }
}ch10_4.jsp
<%--
  Created by IntelliJ IDEA.
  User: CaptainDong
  Date: 2023/5/16
  Time: 17:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>表格数据浏览</title>
    <style>
        #body_style {
            background-color: #c7f5db;
        }
        #myDiv {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            font-size: medium;
            border: 2px solid #28e5d8f0;
            padding: 28px 30px;
            background: #a1eec5;
            width: 350px;
            border-radius: 25px;
            -moz-border-radius: 25px;
        }
    </style>
    <script type="text/javascript" src="js\ajax.js"></script>
    <script type="text/javascript">
        function query(){
            sendRequest("query",null,"POST",show);
        }
        function show(){
            if (httpRequest.readyState==4){
                if (httpRequest.status=200){
                    let tBody=document.getElementById("tBody");
                    tBody.innerHTML="";
                    let studentList=JSON.parse(httpRequest.responseText);
                    for (let index in studentList){
                        let newTr=tBody.insertRow();
                        let newTd1=newTr.insertCell();
                        newTd1.innerHTML=studentList[index].studentNumber;
                        let newTd2=newTr.insertCell();
                        newTd2.innerHTML=studentList[index].studentName;
                        let newTd3=newTr.insertCell();
                        newTd3.innerHTML=studentList[index].studentSex;
                    }
                }
            }
        }
    </script>
</head>
<body id="body_style">
<div id="myDiv">
<a href="javascript:query()">获取表格数据</a><br><br>
    <table  border="7" align="center">
        <tr>
            <th>学号</th><th>姓名</th><th>性别</th>
            <tbody id="tBody"></tbody>
        </tr>
    </table>
</div>
</body>
</html>
student.java
package com.dong;
public class Student {
    private String studentNumber;
    private String studentName;
    private String studentSex;
    public Student() {
    }
    public Student(String studentNumber, String studentName, String studentSex) {
        this.studentNumber = studentNumber;
        this.studentName = studentName;
        this.studentSex = studentSex;
    }
    public String getStudentNumber() {
        return studentNumber;
    }
    public void setStudentNumber(String studentNumber) {
        this.studentNumber = studentNumber;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentSex() {
        return studentSex;
    }
    public void setStudentSex(String studentSex) {
        this.studentSex = studentSex;
    }
}
Query.java
package com.li;
import com.dong.Student;
import net.sf.json.JSONArray;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/query")
public class Query extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        Student student1=new Student("202121555","张三","男");
        Student student2=new Student("202121566","小美","女");
        List<Student>studentList1=new ArrayList<Student>();
        studentList1.add(student1);
        studentList1.add(student2);
        JSONArray jsonArray = JSONArray.fromObject(studentList1);
        out.println(jsonArray.toString());
    }
}
- 这段代码是一个 JSP 页面,用于实现一个简单的 AJAX 表格数据浏览功能。
- 页面包含一个表格和一个按钮,当用户点击按钮时,JavaScript 中的
query()函数被调用。query()函数使用了封装好的sendRequest()函数,向服务器发起了一个异步请求,并指定了请求处理函数为show()。- 当服务器返回响应时,
show()函数被调用。如果响应状态码为 200,则解析服务器返回的 JSON 格式数据,并将其填充到表格中。具体来说,show()函数首先获取到表格的<tbody>元素,并清空其中的所有子元素。然后通过JSON.parse()方法将服务器返回的 JSON 字符串解析成 JavaScript 对象数组,并遍历该数组。在循环中,使用insertRow()、insertCell()和innerHTML等方法动态创建表格的行和列,并将数据填充进去。- 需要注意的是,这里使用了 XMLHttpRequest 对象进行了 AJAX 请求。而
sendRequest()函数则是对 XMLHttpRequest 对象的一次封装,用于简化 AJAX 请求的过程。此外,页面中还定义了一些 CSS 样式,用于美化页面的外观。- 此外,该 JSP 页面引用了一个名为
ajax.js的 JavaScript 文件,用于封装 AJAX 请求相关的代码。该文件中包含了一个名为sendRequest()的函数,用于方便地向服务器发起 AJAX 请求,其调用形式为:sendRequest(url, data, method, callback)。其中,url参数表示请求的 URL 地址,data表示请求数据(可以为空),method表示请求方法,callback表示请求处理完毕后的回调函数。具体实现可以查看ajax.js文件的代码。
运行结果:

点击获取表格后:

基于Ajax+JSon的表格数据浏览【连接数据库版】
分析:
我们需要对上述代码进行如下修改:
首先,在 doGet() 和 doPost() 方法中用 JDBC 连接到数据库。
然后,查询数据库获取学生信息,将其添加到 List 中。
最后,将列表转换为 JSON 格式并作为响应返回给客户端。
修改之后的代码为:
代码:
package com.li;
import com.dong.Student;
import net.sf.json.JSONArray;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
 * 连接数据库获取表格数据
 */
@WebServlet("/queryForm")
public class QueryForm extends HttpServlet {
    private final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    private final String DB_URL = "jdbc:mysql://localhost:3306/test01";
    private final String USER_NAME = "root";
    private final String PASSWORD = "root";
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            /**
             * 连接数据库
             */
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
            /**
             * 查询学生信息
             */
            String sql = "select * from student";
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            List<Student> studentList = new ArrayList<>();
            while (rs.next()) {
                String studentNumber = rs.getString("studentNumber");
                String studentName = rs.getString("studentName");
                String studentSex = rs.getString("studentSex");
                Student student = new Student(studentNumber, studentName, studentSex);
                studentList.add(student);
            }
            //将列表转换为 JSON 格式并发送回客户端
            JSONArray jsonArray = JSONArray.fromObject(studentList);
            out.println(jsonArray.toString());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (stmt != null)
                    stmt.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}//声明XMLHttpRequest对象
var httpRequest=null;
//创建XMLHttpRequest对象实例的方法
function createXHR(){
    if(window.XMLHttpRequest){
        httpRequest=new XMLHttpRequest();
    }else if(window.ActiveXObject){
        try{
            httpRequest=new ActiveXObject("Maxml2.XMLHTTP");//IE较新版
        }catch (e){
            try{
                httpRequest=new ActiveXObject("Microsoft.XMLHTTP");//IE较老版
            }catch (e) {
                httpRequest=null;
            }
        }
    }
    if (!httpRequest){
        alert("fail to create httpRequest!");
    }
}
function sendRequest(url,params,method,handler){
    createXHR();
    if (!httpRequest){
        return false;
    }
    httpRequest.onreadystatechange=handler;
    if(method=="GET"){
        httpRequest.open(method,url+'?'+params,true);
        httpRequest.send(null);
    }
    if (method=="POST"){
        httpRequest.open(method,url,true);
        httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        httpRequest.send(params);
    }
}<%--
Created by IntelliJ IDEA.
User: CaptainDong
Date: 2023/5/16
Time: 17:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>表格数据浏览</title>
    <style>
        #body_style {
            background-color: #c7f5db;
        }
        #myDiv {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            font-size: medium;
            border: 2px solid #28e5d8f0;
            padding: 28px 30px;
            background: #a1eec5;
            width: 350px;
            border-radius: 25px;
            -moz-border-radius: 25px;
        }
    </style>
    <script type="text/javascript" src="js\ajax.js"></script>
    <script type="text/javascript">
        function query01(){
            sendRequest("queryForm",null,"POST",show);
        }
        function show(){
            console.log(httpRequest.responseText); // 打印 HTTP 响应内容
            if (httpRequest.readyState==4){
                if (httpRequest.status==200){
                    let responseText = httpRequest.responseText.trim();
                    if (responseText === ''){
                        alert('服务器返回空数据!');
                        return;
                    }
                    let tBody=document.getElementById("tBody");
                    tBody.innerHTML="";
                    let studentList=JSON.parse(responseText);
                    if(studentList.length === 0){
                        alert("未查询到任何数据!");
                        return; // 结束函数
                    }
                    for (let index in studentList){
                        let newTr=tBody.insertRow();
                        let newTd1=newTr.insertCell();
                        newTd1.innerHTML=studentList[index].studentNumber;
                        let newTd2=newTr.insertCell();
                        newTd2.innerHTML=studentList[index].studentName;
                        let newTd3=newTr.insertCell();
                        newTd3.innerHTML=studentList[index].studentSex;
                    }
                } else {
                    alert('请求发生错误:' + httpRequest.status);
                }
            } else {
                console.log('请求正在发送中...');
            }
        }
    </script>
</head>
<body id="body_style">
<div id="myDiv">
    <a href="javascript:query01()">获取表格数据</a><br><br>
    <table  border="7" align="center">
        <tr>
            <th>学号</th><th>姓名</th><th>性别</th>
            <tbody id="tBody"></tbody>
        </tr>
    </table>
</div>
</body>
</html>package com.dong;
public class Student {
    private String studentNumber;
    private String studentName;
    private String studentSex;
    public Student() {
    }
    public Student(String studentNumber, String studentName, String studentSex) {
        this.studentNumber = studentNumber;
        this.studentName = studentName;
        this.studentSex = studentSex;
    }
    public String getStudentNumber() {
        return studentNumber;
    }
    public void setStudentNumber(String studentNumber) {
        this.studentNumber = studentNumber;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentSex() {
        return studentSex;
    }
    public void setStudentSex(String studentSex) {
        this.studentSex = studentSex;
    }
}


















![【换根DP+容斥】P3047 [USACO12FEB]Nearby Cows G](https://img-blog.csdnimg.cn/994b1cc03c5e44688798d98c1d742f59.jpeg)
