• ajax提交表单数据到controller


    表单

    <div class="addDIV">
    
        <div class="panel panel-success">
            <div class="panel-heading">
                <h3 class="panel-title" style="text-align:center">增加学生</h3>
            </div>
            <div class="panel-body">
    
                <form method="post" id="addForm" onsubmit="return validateForm();" role="form">
                    <table class="addTable">
                        <tr>
                            <td>学号:</td>
                            <td><input type="text" name="student_id" id="student_id" placeholder="请在这里输入学号"></td>
                        </tr>
                        <tr>
                            <td>姓名:</td>
                            <td><input type="text" name="name" id="name" placeholder="请在这里输入名字"></td>
                        </tr>
                        <tr>
                            <td>年龄:</td>
                            <td><input type="text" name="age" id="age" placeholder="请在这里输入年龄"></td>
                        </tr>
                        <tr>
                            <td>性别:</td>
                            <td><input type="radio" checked class="radio radio-inline" name="sex" value=""><input type="radio" class="radio radio-inline" name="sex" value=""></td>
                        </tr>
                        <tr>
                            <td>出生日期:</td>
                            <td><input type="date" name="birthday" id="birthday" placeholder="请在这里输入出生日期"></td>
                        </tr>
                        <tr class="submitTR">
                            <td colspan="2" align="center">
                                <button type="submit" class="btn btn-success">提 交</button>
                            </td>
    
                        </tr>
    
                    </table>
                </form>
            </div>
        </div>
    
    </div>

    js方法

    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <%-- 引入JQ和Bootstrap --%>
        <script src="js/jquery/2.0.0/jquery-2.1.4.js"></script>
        <link href="css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
        <script src="js/bootstrap/3.3.6/bootstrap.min.js"></script>
        <script type="text/javascript" src="js/myjs/list.js"></script>
        <link href="css/style.css" rel="stylesheet">
        <script type="text/javascript">
           $(function(){
            //页面加载初始化发送请求获取json数据。
            $.get(getRootPath()+"/listStudent",
                    //需要传递的数据:pageIndex ,
                    {"pageIndex":"1"},
                    function(data){
                        //1.删除原来的数据
                        $("#datalist").children().remove();
                        $("#pageIndex").children().remove();
                        //2.添加数据
                         eachListStudent(data);
                         eachPageIndex(data);
                    });
        });
    
           $.fn.validate = function(tips){
    
               if($(this).val() == "" || $.trim($(this).val()).length == 0){
                   alert(tips + "不能为空!");
                   return false; //如果验证不通过,则不执行后面
               }
               return true;
           }
           function validateForm(){
               //调用validate()
               var s_id = $("#student_id").validate("学号");
               var s_name = $("#name").validate("姓名");
               var s_age = $("#age").validate("年龄");
               var s_birth = $("#birthday").validate("生日");
               var bool= s_id && s_name && s_age && s_birth;
               return addStudent(bool);
           }
     
           //提交表单数据到controller的addStudent,addStudent再重定向到遍历学生列表的方法
           function addStudent(bool){
               if(bool){
                   //发送请求$("#addForm").serialize() 
                   $.get(getRootPath()+"/addStudent",
                           $("#addForm").serialize(),
                           function(data){
                           alert("成功添加学生");
                   });
               }
               
           } 
         
          
        
        </script>
    </head>

    myjs

        //点击下标查询数据
        function changeIndex(pageIndex){
            //用户点击下标,有下标值,ajax请求,然后要删除表数据和下标数,然后添加表数据和下标数
            $.get(getRootPath()+"/listStudent",
                    //需要传递的数据:pageIndex ,
                    {"pageIndex":pageIndex},
                    function(data){
                        //1.删除原来的数据
                        $("#datalist").html("");
                        $("#pageIndex").html("");
                        //2.添加数据
                           eachListStudent(data); 
                        //3.添加下标数据
                         eachPageIndex(data);
                    });
        }
      //地址获取
           function getRootPath(){
               var rootPath=window.location.pathname; //   /Day517/Ajax.jsp
               var index = rootPath.indexOf("/",1);  // 获得第二个斜杠的下标值
               rootPath = rootPath.substring(0,index); //截取获得从0开始不包括index /Day517  
               return rootPath;
           }
      //遍历学生集合
        function eachListStudent(data){
             data=eval("("+data+")");
                $(data.beanList).each(function(index,student){
                var html="<tr><td>"
                    +student.student_id +"</td><td>"
                    +student.name+"</td><td>"
                    +student.age+"</td><td>"
                    +student.sex+"</td><td>"
                    +student.birthday+"</td><td>"
                    +"<a href="+"""+getRootPath()+"/editStudent?id="+student.id+"">"+"<span class="glyphicon glyphicon-edit"></span> </a></td>"
                    +"<td><a href="+"""+getRootPath()+"/deleteStudent?id="+student.id+" onclick="javascript:return del();"><span class="glyphicon glyphicon-trash"></span> </a></td>" ; 
                    $(html).appendTo("#datalist");
                }); 
        }
          //遍历下标
        function eachPageIndex(data){
            data=eval("("+data+")");
            var html="";
            for(var i=data.beginIndex;i<=data.endIndex;i++){
                //如果是当前页下标,则没有点击切换事件
                    if(i==data.beginIndex){
                        html="<li><a href="javascript:void(0);" onclick="javascript:return changeIndex(1)">&laquo;</a></li>";
                        $(html).appendTo("#pageIndex");
                    }
                    if(data.pageIndex==i){
                            html="<li  class="disabled"><a href="javascript:void(0);">"+i+"</a></li>";
                    }else{
                            html="<li><a href="javascript:void(0);" onclick="javascript:return changeIndex("+i+")">"+i+"</a></li>";
                        }
                        $(html).appendTo("#pageIndex");
                    if(i==data.endIndex){
                             html="<li><a href="javascript:void(0);" onclick="javascript:return changeIndex("+data.totalPage+")">&raquo;</a></li>";
                             $(html).appendTo("#pageIndex");
                    }
             }
        }

    后台代码

    @Controller
    @RequestMapping("")
    public class StudentController {
    
        @Autowired
        private StudentService studentService;
    
        @RequestMapping("/addStudent")
        public String addStudent(HttpServletRequest request, HttpServletResponse response) {
    
            Student student = new Student();
    
            int studentID = Integer.parseInt(request.getParameter("student_id"));
            System.out.println("studentID:"+studentID);
            String name = request.getParameter("name");
            int age = Integer.parseInt(request.getParameter("age"));
            String sex = request.getParameter("sex");
            Date birthday = null;
            // String 类型按照 yyyy-MM-dd 的格式转换为 java.util.Date 类
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                birthday = simpleDateFormat.parse(request.getParameter("birthday"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
    
            student.setStudent_id(studentID);
            student.setName(name);
            student.setAge(age);
            student.setSex(sex);
            student.setBirthday(birthday);
    
            studentService.addStudent(student);
            return "redirect:listStudent";
        }
        
        
        /**
         * 分页查询
         * @param request
         * @param response
         * @return
         * @throws IOException 
         */
        @RequestMapping("/listStudent")
        public void listStudentByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.setCharacterEncoding("UTF-8");
            String paramPageIndex = request.getParameter("pageIndex");
            int pageIndex=1;
            if("".equals(paramPageIndex)||paramPageIndex==null) {
                pageIndex=1;
            }else {
                pageIndex=Integer.parseInt(paramPageIndex);
            }
            PageBean<Student> pageBean = studentService.getPageBean(pageIndex, 10);
            JSONObject json =  JSONObject.fromObject(pageBean);
            PrintWriter writer = response.getWriter();
            writer.write(json.toString());
        }
       
    
        
        
        @RequestMapping("/deleteStudent")
        public String deleteStudent(int id) {
            studentService.deleteStudent(id);
            return "redirect:listStudent";
        }
    
        
        
        @RequestMapping("/editStudent")
        public ModelAndView editStudent(int id) {
            ModelAndView mav = new ModelAndView("editStudent");
            Student student = studentService.getStudent(id);
            mav.addObject("student", student);
            return mav;
        }
    
        @RequestMapping("/updateStudent")
        public String updateStudent(HttpServletRequest request, HttpServletResponse response) {
    
            Student student = new Student();
    
            int id = Integer.parseInt(request.getParameter("id"));
            int student_id = Integer.parseInt(request.getParameter("student_id"));
            String name = request.getParameter("name");
            int age = Integer.parseInt(request.getParameter("age"));
            String sex = request.getParameter("sex");
    
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = null;
            try {
                birthday = simpleDateFormat.parse(request.getParameter("birthday"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
    
            student.setId(id);
            student.setStudent_id(student_id);
            student.setName(name);
            student.setAge(age);
            student.setSex(sex);
            student.setBirthday(birthday);
    
            studentService.updateStudent(student);
            return "redirect:listStudent";
        }
    }

    https://blog.csdn.net/jiangyu1013/article/details/72179611 添加除了表单参数外的其他参数,也可以使用隐藏标签hidden

  • 相关阅读:
    JavaScript 检测对象类型
    memorize
    高阶函数
    JavaScript 中的不完全函数
    VS C# Winform 重写进度条
    使用ECLIPSE+RED搭建RF自动化测试框架
    NOIP2018濒死记
    HDU 5977 Garden of Eden (树形dp+快速沃尔什变换FWT)
    打FFT时中发现的卡常技巧
    Dynamic Rankings || 动态/静态区间第k小(主席树)
  • 原文地址:https://www.cnblogs.com/19322li/p/11089909.html
Copyright © 2020-2023  润新知