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


同步提交: 
html:

<form id="form" method='"post" action="${ctx}/user/saveUser">
    <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="submit" value="保存"/>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

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";
    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

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";
        }
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值