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";
        }
    }
發佈了2 篇原創文章 · 獲贊 7 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章