同步提交:html
html: <form id="form" method='"post" action="${ctx}/user/saveUser"> ajax
<input type="text" id="name" name="name" value="${user.name}"/> 服務器
<input type="text" id="age" name="age" value="${user.age}"/>app
</form>異步
<input id="save-btn" type="submit" value="保存"/>async
controller: @RequestMapping(value = "/saveUser",method = RequestMethod.POST) 函數
public String saveUser(User user,HttpServletRequest request, HttpServletResponse response) throws Exception { post
try{ url
userService.save(user); orm
}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(),
async:false,
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";
}
}
ajax同步提交:若是將async改爲true(true同步,false異步),不等服務器返回就會直接返回false,寫這類函數的時候要注意把async設置成false
同步提交是指等待服務器響應後在進行後面的操做,異步提交不用等待服務器響應就會進行後面的操做
同步和異步的區別: