ajax请求实现学生信息的增删改查
创建数据库/表:
运行结果:
查找:
添加:
修改:
增删改查之后的数据表:
页面整体布局:
代码部分:
创建数据库/表:
创建数据库:
#创建数据库
create database 70806_db
default character set utf8mb4 #设置字符集
default collate utf8mb4_general_ci #设置排序规则
创建数据表:
#创建班级表
create table classInfo
(
classId int primary key auto_increment,
className varchar(20)
);
select * from classInfo;
insert into classInfo
(className)
values
('AAA01'),
('AAA02');
#创建学生表
create table studentInfo
(
studentId int primary key auto_increment,
name varchar(20) not null,
sex char(1) not null,
birthday date,
province varchar(20) default '河南',
classId int,
foreign key (classId)
references classInfo(classId)
);
select * from studentInfo;
insert into studentInfo
(name,sex,birthday,province,classId)
values
('张三','男','2002-01-01','湖北',1),
('李四','女','2003-01-05','河南',2),
('王五','男','2010-03-01','湖北',1),
('赵六','男','2009-01-08','河南',2),
('孙琪','女','2001-09-01','湖北',1);
util:
BaseDAO:
package com.util;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.*;
public class BaseDAO {
//四大金刚
//驱动类
private static final String DRIVER="com.mysql.cj.jdbc.Driver";
//连接地址
private static final String URL="jdbc:mysql://localhost:3306/70806_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
//用户名
private static final String USER="root";
//密码
private static final String PASSWORD="123456";
//获取连接
public static Connection getConnection(){
Connection con = null;
try{
//加载驱动类
Class.forName(DRIVER);
//获取连接
con = DriverManager.getConnection(URL,USER,PASSWORD);
}catch(Exception ex){
ex.printStackTrace();
}
return con;
}
//关闭数据库对象
public static void closeAll(Connection con,Statement st,ResultSet rs){
if(rs!=null){
try{
rs.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(st!=null){
try{
st.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(con!=null){
try{
con.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
//通用设置参数方法
public static void setParams(PreparedStatement pst,Object[] params){
if(params==null){
return;
}
for(int i=0;i<params.length;i++){
try{
pst.setObject(i+1,params[i]);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
//通用增删改
public static int executeUpdate(String sql,Object[] params){
Connection con = null;
PreparedStatement pst = null;
int res = -1;
try{
//获取连接
con = getConnection();
//创建预编译命令执行对象
pst = con.prepareStatement(sql);
//设置参数
setParams(pst,params);
//执行
System.out.println(pst);
res = pst.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll(con,pst,null);
}
return res;
}
//获取总记录数的查询:select count(*) from ..
public static int getTotal(String sql,Object[] params){
int total = 0;
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
con = getConnection();
pst = con.prepareStatement(sql);
setParams(pst,params);
rs = pst.executeQuery();
//判断是否查询除了一个记录
if(rs.next()){
total = rs.getInt(1);
}
}catch (Exception ex){
ex.printStackTrace();
}finally {
closeAll(con,pst,rs);
}
return total;
}
//通用查询
public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {
List<Map<String,Object>> rows = new ArrayList<>();
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
//获取连接
con = getConnection();
//获取命令对象
pst = con.prepareStatement(sql);
//设置参数
setParams(pst,params);
//执行查询
rs = pst.executeQuery();
//通过rs获取结果集的结构信息
ResultSetMetaData rsmd = rs.getMetaData();
//获取结果集的列数
int colCount = rsmd.getColumnCount();
//遍历查询结果,并封装到List<Map>中
while(rs.next()){
//用Map存储当前行的各个列数据
Map<String,Object> map = new HashMap<>();
//循环获取每一列的信息
for(int i=1;i<=colCount;i++){
//获取列名(使用rsmd)
String colName = rsmd.getColumnLabel(i);
//获取列值(使用rs)
Object colVal = rs.getObject(i);
//将当前列存储到map中
map.put(colName,colVal);
}
//将遍历的当前行的数据存储到List中
rows.add(map);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll(con,pst,rs);
}
return rows;
}
}
entity:
Student:
package com.entity;
import java.util.Date;
public class Student {
private Integer studentId;
private String name;
private String sex;
private Date birthday;
private String province;
private Integer classId;
public Student() {
}
public Student(Integer studentId, String name, String sex, Date birthday, String province, Integer classId) {
this.studentId = studentId;
this.name = name;
this.sex = sex;
this.birthday = birthday;
this.province = province;
this.classId = classId;
}
public Student(String name, String sex, Date birthday, String province, Integer classId) {
this.name = name;
this.sex = sex;
this.birthday = birthday;
this.province = province;
this.classId = classId;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", province='" + province + '\'' +
", classId=" + classId +
'}';
}
}
ClassInfo:
package com.entity;
public class ClassInfo {
private Integer classId;
private String className;
public ClassInfo() {
}
public ClassInfo(String className) {
this.className = className;
}
public ClassInfo(Integer classId, String className) {
this.classId = classId;
this.className = className;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@Override
public String toString() {
return "ClassInfo{" +
"classId=" + classId +
", className='" + className + '\'' +
'}';
}
}
PageData:
package com.entity;
public class PageData {
//当前页码
private Integer pageNo;
//每页记录数
private Integer pageSize;
//总记录数
private Integer totalCount;
//总页数
private Integer totalPage;
//当前页记录
private Object data;
public PageData() {
}
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "PageData{" +
"pageNo=" + pageNo +
", pageSize=" + pageSize +
", totalCount=" + totalCount +
", totalPage=" + totalPage +
", data=" + data +
'}';
}
}
dao:
impl:
IStudentDAO:
package com.dao;
import com.entity.PageData;
import com.entity.Student;
import java.util.List;
import java.util.Map;
public interface IStudentDAO {
List<Map<String,Object>> listAll();
int insert(Student student);
int update(Student student);
PageData queryByPage(Integer pageNo, Integer pageSize);
}
IClassInfoDAO:
package com.dao;
import java.util.List;
import java.util.Map;
public interface IClassInfoDAO {
List<Map<String ,Object>> listAll();
}
StudentDAOImpl:
package com.dao.impl;
import com.dao.IStudentDAO;
import com.entity.PageData;
import com.entity.Student;
import com.util.BaseDAO;
import java.util.List;
import java.util.Map;
public class StudentDAOImpl implements IStudentDAO {
@Override
public List<Map<String, Object>> listAll() {
System.out.println("=======StudentDAOImpl listAll===============");
String sql = "select s.studentId,s.name,s.sex,s.birthday,s.province," +
" c.classId,c.className " +
" from studentInfo s " +
" join classInfo c " +
" on s.classId = c.classId ";
System.out.println(sql);
return BaseDAO.executeQuery(sql,null);
}
@Override
public int insert(Student student) {
String sql="insert into studentInfo "+
" (name,sex,birthday,province,classId)"+
" values"+
" (?,?,?,?,?)";
Object[] params={
student.getName(),
student.getSex(),
student.getBirthday(),
student.getProvince(),
student.getClassId()
};
return BaseDAO.executeUpdate(sql,params);
}
@Override
public int update(Student student) {
String sql = "update studentInfo" +
" set name = ?," +
" sex = ?," +
" birthday = ?," +
" province = ?," +
" classId = ? " +
" where studentId = ? ";
Object[] params = {
student.getName(),
student.getSex(),
student.getBirthday(),
student.getProvince(),
student.getClassId(),
student.getStudentId()
};
return BaseDAO.executeUpdate(sql,params);
}
@Override
public PageData queryByPage(Integer pageNo, Integer pageSize) {
//获取总记录数
String totalSql = "select count(*) from studentInfo ";
//总记录数
Integer totalCount = BaseDAO.getTotal(totalSql,null);
//总页数
Integer totalPage = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
//分页查询
String pageSql = "select s.studentId,s.name,s.sex,s.birthday,s.province," +
" c.classId,c.className " +
" from studentInfo s " +
" join classInfo c " +
" on s.classId = c.classId " +
" order by s.studentId " +
" limit ?,? ";
int start = (pageNo-1)*pageSize;
Object[] params = {start,pageSize};
List<Map<String,Object>> rows = BaseDAO.executeQuery(pageSql,params);
//封装分页数据对象
PageData pd = new PageData();
pd.setPageNo(pageNo);
pd.setPageSize(pageSize);
pd.setTotalPage(totalPage);
pd.setTotalCount(totalCount);
pd.setData(rows);
return pd;
}
}
ClassInfoDAOImpl:
package com.dao.impl;
import com.dao.IClassInfoDAO;
import com.util.BaseDAO;
import java.util.List;
import java.util.Map;
public class ClassInfoDAOImpl implements IClassInfoDAO {
@Override
public List<Map<String, Object>> listAll() {
String sql="select classId,className from classInfo";
return BaseDAO.executeQuery(sql,null);
}
}
service:
impl:
IStudentService:
package com.service;
import com.entity.PageData;
import com.entity.Student;
import java.util.List;
import java.util.Map;
public interface IStudentService {
List<Map<String,Object>> listAll();
//添加学生
int add(Student student);
int update(Student student);
PageData queryByPage(Integer pageNo, Integer pageSize);
}
IClassInfoService:
package com.service;
import java.util.List;
import java.util.Map;
public interface IClassInfoService {
List<Map<String,Object>> listAll();
}
StudentServiceImpl:
package com.service.impl;
import com.dao.IStudentDAO;
import com.dao.impl.StudentDAOImpl;
import com.entity.PageData;
import com.entity.Student;
import com.service.IStudentService;
import com.util.BaseDAO;
import java.util.List;
import java.util.Map;
public class StudentServiceImpl implements IStudentService {
private IStudentDAO studentDAO=new StudentDAOImpl();
@Override
public int update(Student student) {
return studentDAO.update(student);
}
@Override
public PageData queryByPage(Integer pageNo, Integer pageSize) {
return studentDAO.queryByPage(pageNo,pageSize);
}
@Override
public int add(Student student) {
return studentDAO.insert(student);
}
@Override
public List<Map<String, Object>> listAll() {
return studentDAO.listAll();
}
}
ClassInfoServiceImpl:
package com.service.impl;
import com.dao.IClassInfoDAO;
import com.dao.impl.ClassInfoDAOImpl;
import com.service.IClassInfoService;
import java.util.List;
import java.util.Map;
public class ClassInfoServiceImpl implements IClassInfoService {
private IClassInfoDAO classInfoDAO=new ClassInfoDAOImpl();
@Override
public List<Map<String, Object>> listAll() {
return classInfoDAO.listAll();
}
}
servlet:
StudentServlet :
package com.servlet;
import com.alibaba.fastjson.JSONObject;
import com.entity.Student;
import com.mysql.cj.util.StringUtils;
import com.service.IStudentService;
import com.service.impl.StudentServiceImpl;
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.util.Date;
import java.util.HashMap;
import java.util.Map;
@WebServlet(urlPatterns = "/StudentServlet/*")
public class StudentServlet extends HttpServlet {
private IStudentService studentService = new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求方法
String uri = req.getRequestURI();
String process = uri.substring(uri.lastIndexOf("/")+1);
System.out.println("proccess:"+process);
// //设置响应编码
// resp.setContentType("text/html;charset=utf-8");
//定义处理之后返回的数据对象
Object data = null;
switch (process){
case "query":
data = this.query(req,resp);
break;
case "queryByPage":
data = this.queryByPage(req,resp);
break;
case "add":
data=this.add(req,resp);
break;
case "update":
data = this.update(req,resp);
break;
}
System.out.println("data:"+data);
//将数据转为json字符串
String jsonStr = JSONObject.toJSONStringWithDateFormat(data,"yyyy-MM-dd");
System.out.println(jsonStr);
PrintWriter out = resp.getWriter(); //获取输出流对象
out.println(jsonStr); //输出json字符串给浏览器
out.flush(); //清空缓存
out.close();//关闭流对象
}
private Object queryByPage(HttpServletRequest req, HttpServletResponse resp) {
//获取前端传入的分页参数
String pageNo = req.getParameter("pageNo");
String pageSize = req.getParameter("pageSize");
//判断参数是否有效
Integer pn = StringUtils.isNullOrEmpty(pageNo)?1:Integer.parseInt(pageNo);
Integer ps = StringUtils.isNullOrEmpty(pageSize)?3:Integer.parseInt(pageSize);
return studentService.queryByPage(pn,ps);
}
private Object update(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("111");
//获取传入的数据
Integer studentId = Integer.parseInt(req.getParameter("studentId"));
String name = req.getParameter("name");
String sex = req.getParameter("sex");
Date birthday = java.sql.Date.valueOf(req.getParameter("birthday"));
String province = req.getParameter("province");
Integer classId = Integer.parseInt(req.getParameter("classId"));
//封装实体对象
Student student = new Student(
studentId,name,sex,birthday,province,classId
);
//调用业务层保存数据
int count = studentService.update(student);
System.out.println("count:"+count);
//定义结果数据
Map<String,Object> res = new HashMap<>();
//添加成功
if(count==1){
//code为0说明处理成功
res.put("code",0);
}else{
//code为1处理失败
res.put("code",1);
}
System.out.println("res:"+res);
return res;
}
//添加
private Object add(HttpServletRequest req, HttpServletResponse resp) {
//获取传入的数据
String name=req.getParameter("name");
String sex=req.getParameter("sex");
Date birthday=java.sql.Date.valueOf(req.getParameter("birthday"));
String province=req.getParameter("province");
Integer classId=Integer.parseInt(req.getParameter("classId"));
//封装实体对象
Student student=new Student(
name,sex,birthday,province,classId
);
//调用业务层保存数据
int count= studentService.add(student);
//定义数据结果
Map<String,Object> res=new HashMap<>();
//添加成功
if(count==1){
//code为0说明处理成功
res.put("code",0);
}else{
//code为1处理失败x`
res.put("code",1);
}
return res;
}
/**
* 执行查询
* @param req
* @param resp
* @return
*/
private Object query(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("=====StudentServlet query=======");
return studentService.listAll();
}
}
ClassInfoServlet :
package com.servlet;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonString;
import com.service.IClassInfoService;
import com.service.impl.ClassInfoServiceImpl;
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;
@WebServlet("/ClassInfoServlet/*")
public class ClassInfoServlet extends HttpServlet {
//业务层对象
private IClassInfoService classInfoService=new ClassInfoServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri=req.getRequestURI();
String process=uri.substring(uri.lastIndexOf("/")+1);
//定义结果对象
Object date=null;
switch (process){
case "query":
date=query(req,resp);
break;
}
//输出json字符串
String jsonStr= JSONObject.toJSONString(date);
PrintWriter out=resp.getWriter();
out.println(jsonStr);
out.flush();
out.close();
}
//查村
private Object query(HttpServletRequest req, HttpServletResponse resp) {
return classInfoService.listAll();
}
}
filter:
CharacterEncodingFilter:
package com.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//设置编码
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
//向后传递请求
filterChain.doFilter(servletRequest,servletResponse);
}
}
web:
index.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/8/5
Time: 11:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$ <a href="${pageContext.request.contextPath}/student.jsp">学生表</a>
</body>
</html>
student.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/8/8
Time: 1:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style type="text/css">
/*遮罩层*/
#cover{
position: absolute;
z-index: 1;
left: 0px;
top: 0px;
bottom: 0px;
right: 0px;
background-color: black;
opacity: 0.8; /*设置透明度*/
display: none; /* 将遮罩层设置为隐藏 */
}
#stuDiv{
position: absolute;
z-index: 9;
border:5px solid gray;
width: 300px;
padding: 10px;
background-color: white;
display: none;
}
#stuDiv table{
width: 100%;
}
</style>
</head>
<body>
<table border="1" align="center">
<thead>
<tr>
<td colspan="7">
<input type="button" value="添加" id="btnAdd" />
</td>
</tr>
<tr>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>生日</th>
<th>省份</th>
<th>班级</th>
<th>操作</th>
</tr>
</thead>
<tbody id="stuBody">
</tbody>
</table>
<!--弹出层遮罩-->
<div id="cover"></div>
<!--弹出层表单-->
<div id="stuDiv">
<form id="stuFrm">
<input type="hidden" name="studentId"/>
<table border="1" >
<tr>
<td>姓名</td>
<td>
<input type="text" name="name" id="name"/>
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女
</td>
</tr>
<tr>
<td>生日</td>
<td>
<input type="date" name="birthday"/>
</td>
</tr>
<tr>
<td>省份</td>
<td>
<select name="province">
<option value="">请选择</option>
<option value="河南">河南</option>
<option value="河北">河北</option>
<option value="山东">山东</option>
<option value="湖北">湖北</option>
</select>
</td>
</tr>
<tr>
<td>班级</td>
<td>
<select name="classId" id="classId">
<option value="">请选择</option>
<!--用循环生成-->
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="保存" id="btnSave"/>
<input type="button" value="取消" id="btnCancel"/>
</td>
</tr>
</table>
</form>
</div>
<!--引入jq-->
<script type="text/javascript" src="${pageContext.request.contextPath}/assets/plugins/jq/jquery-1.12.4.min.js"></script>
<!--定义自己的代码块-->
<script type="text/javascript">
//SPA: single page application 单页面应用
//页面加载完成
$(function (){
//调整表单层位置
adjustStuDivPos();
//绑定添加按钮单击事件
bindAddBtn();
//绑定表单中的保存按钮
bindSaveBtn();
//绑定表单中的取消按钮
bindCancelBtn();
//加载班级数据
loadClassInfo();
//调用查询
query();
})
//加载班级的数据到下拉框中
function loadClassInfo(){
$.ajax({
url:"${pageContext.request.contextPath}/ClassInfoServlet/query",
type:"get",
//data:{},
dataType:"json", //将服务器数据转为什么格式
success:function (res){
//打印输出
console.log(res);
//遍历班级数组数据
$(res).each(function (){
//将遍历的每个班级数据,添加到下拉框中。this就是当前遍历的数据元素
$("#classId").append(
$("<option value='"+this.classId+"'>"+this.className+"</option>")
)
});
},
error:function(xhr,msg){
alert("出错了:"+msg);
}
});
}
//取消按钮
function bindCancelBtn(){
$("#btnCancel").click(function (){
//隐藏遮罩层
$("#cover,#stuDiv").hide();
clearStuFrm();
})
}
//点击保存按钮,实现数据的添加或修改
function bindSaveBtn(){
$("#btnSave").click(function (){
//点击保存时,要判断添加操作还是修改操作,从而设置对应的url
var url = "";
//有studentId说明要修改,没有说明要添加
if($("input[name='studentId']").val()!=""){
url="${pageContext.request.contextPath}/StudentServlet/update";
}else{
url="${pageContext.request.contextPath}/StudentServlet/add";
}
alert(url);
//添加操作
//通过表单序列,返回表单的字符串拼接数据 :name=xxx&sex=xx&age=111
var fd=$("#stuFrm").serialize();
$.ajax({
url:url,
type:"post",
data:fd,
dataType:"json",
success:function(res){
console.log(res);
//判断服务器返回的消息,是否成功
if(res.code==0){
//关闭窗口
$("#cover,#stuDiv").hide();
//清空数据
clearStuFrm();
//处理成功
query();
}else {
//处理失败
alert("处理失败");
}
},
error:function (xhr,msg){
alert("错误:"+msg);
}
})
})
}
//清空表单数据
function clearStuFrm(){
$("input[name='studentId']").val("");
$("input[name='name']").val("");
//设置单选按钮
$("input[value='男']").prop("checked",false);
$("input[value='女']").prop("checked",false);
$("input[name='birthday']").val("");
$("select[name='province']").val("");
$("select[name='classId']").val("");
}
//绑定修改按钮
function bindUpdateBtn(stu){
//显示表单并设置数据
$("#cover,#stuDiv").show();
//设置数据
$("input[name='studentId']").val(stu.studentId);
$("input[name='name']").val(stu.name);
//设置单选按钮
$("input[value='男']").prop("checked",stu.sex=="男");
$("input[value='女']").prop("checked",stu.sex=="女");
$("input[name='birthday']").val(stu.birthday);
$("select[name='province']").val(stu.province);
$("select[name='classId']").val(stu.classId);
}
//绑定添加按钮
function bindAddBtn(){
$("#btnAdd").click(function (){
//显示遮罩层和表单层
// $("cover").show();
// $("stuDiv").show();
$("#cover,#stuDiv").show();
// //在ajax应用中跳转页面
// window.location.href="http://www.baidu.com";
})
}
//调整弹出表单的位置
function adjustStuDivPos(){
//调整表单层位置
var winWidth=$(document).width();
var divWidth=$("#stuDiv").width();
$("#stuDiv").css("left",(winWidth-divWidth)/2);
}
//查询
function query(){
//查之前,先清空之前的数据
$("#stuBody").empty();
$.ajax({
url:"${pageContext.request.contextPath}/StudentServlet/query",
type:"get",
data:{},
dataType:"json",
success:function (res){
//输出查询的数据结果
console.log(res);
//遍历服务器返回的json数组
for(var i=0;i<res.length;i++){
var stu = res[i];
var tr = "";
tr+="<tr>";
tr+="<td>"+stu.studentId+"</td>";
tr+="<td>"+stu.name+"</td>";
tr+="<td>"+stu.sex+"</td>";
tr+="<td>"+stu.birthday+"</td>";
tr+="<td>"+stu.province+"</td>";
tr+="<td>"+stu.className+"</td>";
tr+="<td><input type='button' value='修改' onclick='bindUpdateBtn("+JSON.stringify(stu)+")'/></td>";
tr+="</tr>";
//添加到tbody中
$("#stuBody").append(tr);
}
},
error:function (xhr,msg){
alert("错误:"+msg);
}
});
}
</script>
</body>
</html>
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118067.html