1. 程式人生 > >ajax(三)

ajax(三)

兩個檔案:

jqshow.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
        $(function () {
            function show() {
                $.ajax({
                    type: "POST",
                    url: "/show.do",
                    dataType: "json",
                    data: {action: "show"},
                    success: function (d) {
                        //清除除第一行之外的行
                        $("#st").find("tr:not(:first)").remove();
                        for (i in d) {
                            //$("#st").append("<tr><td>3<td><td>hello<td><tr>")
                            $("#st").append("<tr><td>" + d[i].id + "</td><td>" + d[i].name + "</td><td>" + d[i].score + "</td><td>" + d[i].dept + "</td><td><a href='javaxcript:void(0)' did='" + d[i].id + "'> 刪除</a></td></tr>");
                        }

                        $("a[did]").click(function () {
                            var did = $(this).attr("did");
                            $.get("/show.do", {
                                action: "delete",
                                id: did
                            }, show)
                        });

                    }
                })


            }

            show();

            $('#btnsave').click(function () {
                $.ajax({
                    type: "POST",
                    url: "/show.do",
                    dataType: "text",
                    data: {
                        action: 'save',
                        name: $("#name").val(),
                        score: $("#score").val(),
                        dept: $("#dept").val(),
                        birthday: $("#birthday").val(),
                        money: $("#money").val(),

                    },
                    success: show()
                })
            })

            $("#name").keyup(function () {
                var nn = $(this).val();
                $.ajax({
                    type: "POST",
                    url: "/show.do",
                    dataType: "text",
                    data: {
                        action: "checkstu",
                        name: nn
                    },
                    success: function (d) {
                        if (d == "1") {
                            $("#info").css("color", "green").html("恭喜,此姓名可以使用...")

                        } else {
                            $("#info").css("color", "red").html("註冊失敗,此姓名不可以使用...")
                        }
                    }
                })
            })


        })

    </script>

    <style>

        table.stuu {
            width: 60%;
            margin: 20px auto;
            text-align: center;
            font-family: verdana, arial, sans-serif;
            font-size: 11px;
            color: #333333;
            border: 1px #a9c6c9;
            border-collapse: collapse;
        }

        table.stuu th {
            padding: 8px;
            border: 1px solid #a9c6c9;
        }

        table.stuu td {
            padding: 8px;
            border: 1px solid #a9c6c9;
        }
    </style>

</head>
<body>
<h3>新增學生資料</h3>
姓名:<input type="text" id="name" value="jack">&nbsp;&nbsp;<span id="info"></span><br>
成績:<input type="text" id="score" value="80"><br>
出生日期 :<input type="text" id="birthday" value="1920-10-3">1985-10-25<br>
金額:<input type="text" id="money" value="1000"><br>
專業:<input type="text" id="dept" value="英語"><br>
<input type="button" value="新增儲存" id="btnsave">

<hr>
<br>
<table id="st" class="stuu">
    <tr>
        <th>學號</th>
        <th>姓名</th>
        <th>成績</th>
        <th>專業</th>
        <th>基本操作</th>
    </tr>
</table>

</body>
</html>

show.java

package com.zit.servlet;


import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/show.do")
public class Show extends HttpServlet {
    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dt_game?useSSL=false&serverTimezone=PRC&user=root&password=");
            /* PrintWriter out = resp.getWriter();*/
            String action = req.getParameter("action");

            if ("save".equals(action)) {
                PreparedStatement ast = conn.prepareStatement("insert into stuu values(null,?,?,?,?,?)");
                ast.setString(1, req.getParameter("name"));
                ast.setInt(2, Integer.parseInt(req.getParameter("score")));
                ast.setString(3, req.getParameter("birthday"));
                ast.setDouble(4, Double.parseDouble(req.getParameter("money")));
                ast.setString(5, req.getParameter("dept"));
                ast.executeUpdate();
            } else if ("checkstu".equals(action)) {
                PrintWriter out = resp.getWriter();
                PreparedStatement cst = conn.prepareStatement("select count(*) from stuu where name=?");
                cst.setString(1, req.getParameter("name"));
                ResultSet st = cst.executeQuery();
                st.next();
                if (st.getInt(1) == 0) {
                    out.print("1");
                } else {
                    out.print("0");
                }
            } else if ("delete".equals(action)) {
                PreparedStatement dst = conn.prepareStatement("delete from stuu where id=?");
                dst.setInt(1, Integer.parseInt(req.getParameter("id")));
                dst.executeUpdate();
            } else if ("show".equals(action)) {
                PreparedStatement pst = conn.prepareStatement("select id,name,score,dept from stuu order by id desc ");
                ResultSet rs = pst.executeQuery();
                resp.setContentType("text/html;charset=utf-8");
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                while (rs.next()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", rs.getInt("id"));
                    map.put("name", rs.getString("name"));
                    map.put("score", rs.getString("score"));
                    map.put("dept", rs.getString("dept"));
                    list.add(map);
                }
                PrintWriter out = resp.getWriter();
                out.print(JSONObject.toJSON(list));
                out.flush();
                out.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}