ajax
程序员文章站
2022-07-12 18:07:20
...
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Title</title>
<script src="js/jquery-3.0.0.min.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>" + d[i].id + "</td><td>" + d[i].name + "</td><td>" + d[i].score + "</td><td>" + d[i].dept + "</td><td><a href='javascript:void(0)' did='"+d[i].id+"'>删除</a></td></tr>");
}
$('a[did]').click(function(){
var nnn = $(this).parent().prev().prev().prev().html();
if(confirm('是不是删除:'+ nnn +'?')) {
var did = $(this).attr('did');
$.get('/show.do', {action: 'delete', id: did},show)
}
});
}
});
}
show();
$('#btnsave').click(function(){
$.ajax({
type: 'POST',
url: '/show.do',
dateType: '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.myt {
border: none;
border-collapse: collapse;
color: #333;
width: 800px;
margin: 20px auto;
}
table.myt td {
border: 1px solid #dedede;
text-align: center;
padding: 15px 0;
line-height: 21px;
color: #333;
}
table.myt tr.title {
border-collapse: collapse;
font-weight: bold;
background-color: #f7f7f7;
text-align: center;
color: #333;
width: 789px;
}
</style>
</head>
<body>
<h3>添加学生数据</h3>
姓名:<input type="text" id="name" value="Jack"> <span id="info"></span><br>
成绩:<input type="text" id="score" value="88"><br>
出生日期:<input type="text" id="birthday" value="1985-10-25">1985-10-26<br>
金额:<input type="text" id="money" value="200"><br>
专业:<input type="text" id="dept" value="计算机网络"><br>
<input type="button" value="添加保存" id="btnsave">
<hr>
<br>
<table id="st" class="myt">
<tr class="title">
<td>学号</td>
<td>姓名</td>
<td>成绩</td>
<td>专业</td>
<td>基本操作</td>
</tr>
</table>
</body>
</html>
package com.servlet;
import com.alibaba.fastjson.JSONObject;
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 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;
/**
* Created by Administrator on 2018-09-12.
*/
@WebServlet("/show.do")
public class Show extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db?useSSL=false&serverTimezone=PRC&user=root");
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 (req.getParameter("term")!=null) {
PreparedStatement ppt = conn.prepareStatement("select name from stuu where name like ? limit 5");
ppt.setString(1,"%"+ req.getParameter("term") +"%");
List<String> str = new ArrayList<String>();
ResultSet rss = ppt.executeQuery();
while(rss.next()){
str.add(rss.getString("name"));
}
out.print(JSONObject.toJSON(str));
} else if ("checkstu".equals(action)) {
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();
// StringBuilder s = new StringBuilder();
// s.append("[");
// while(rs.next()){
// String json = String.format("{\"id\":%d,\"name\":\"%s\",\"score\":%d,\"dept\":\"%s\"},",rs.getInt("id"),rs.getString("name"),rs.getInt("score"),rs.getString("dept"));
// s.append(json);
// }
// s.replace(s.length()-1,s.length(),"]");
// out.print(s.toString());
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", rs.getInt("id"));
map.put("name", rs.getString("name"));
map.put("score", rs.getInt("score"));
map.put("dept", rs.getString("dept"));
list.add(map);
}
out.print(JSONObject.toJSON(list));
}
} catch (Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
}
}
上一篇: ajax get 传中文
下一篇: JS代码URL传中文参数乱码