form表单同步提交和异步提交

同步提交:
html:

<form id="form" method='"post" action="${ctx}/user/saveUser">
    
    

controller:

@RequestMapping(value = "/saveUser",method = RequestMethod.POST)
    public String saveUser(User user,HttpServletRequest request, HttpServletResponse response) throws Exception {
        try{
            userService.save(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/user/userList";
    }

ajax异步提交:
注意:form标签去掉method和action属性,保存按钮input标签类型变为button
* controller方法中返回String,则ajax中dataType类型为’text’, *
html:

<form id="form">
    <input type="text" id="name" name="name" value="${user.name}"/>
    <input type="text" id="age" name="age" value="${user.age}"/>
form>
<input id="save-btn" type="button" value="保存"/>
<script>
    $(document).ready(function() {
            //表单异步提交
            $("#save-btn").on("click",function(){
                $.ajax({ 
                    type: 'post', 
                    data: $('#form').serialize(), 
                    url: '${ctx}/user/saveUser',
                    cache:false,  
                    dataType:'text', 
                    success: function (data) {
                        if("fail"!=data){
                            layer.msg('保存成功');
                            window.location.href = "${ctx}/user/userList?userId="+data;
                        }else{
                            layer.msg('保存失败');
                        }
                    }   
                })
            })
script>

controller:

@RequestMapping(value = "/saveUser",method = RequestMethod.POST)
    public String saveUser(User user,HttpServletRequest request, HttpServletResponse response) throws Exception {
        try{
            User user = userService.save(user);
            return user.getUserId();
        }catch (Exception e){
            e.printStackTrace();
            return "fail";
        }
    }

你可能感兴趣的:(web开发,表单,异步)