今天在开发一个用户信息更新模块的时候遇到了两个问题:
一、在我提交form表单的时候我但愿在提交表单以后页面不刷新,同时返回更新数据
二、向后台POST表单信息的时候,后台显示POST url 404的错误javascript
解决第一个问题的使用使用jquery.form的插件进行异步提交java
<script type="text/javascript" src="jquery/jquery.js"></script></head> <script type="text/javascript" src="jquery/jquery.form.js"></script> $(function() { $("#user-update").submit(function(){ $(this).ajaxSubmit({ type:"post", //提交方式 dataType:"json", //数据类型 url:"${pageScope.basePath}user/update", //请求url success:function(data){ //提交成功的回调函数 layer.alert("保存成功"); } }); return false; //不刷新页面 }); });
个人form表单是这个样子的jquery
<form class="am-form" id="user-update" method="POST" > <fieldset> <h4>用户信息</h4> <input value name="id" style="display:none"/> <div class="am-form-group"> <label for="doc-vld-name-2">用户名:</label> <input type="text" name="username" autocomplete="off" valuerequired/> </div> <div class="am-form-group"> <label for="doc-vld-name-2">用户中文名:</label> <input type="text" name="chineseName" autocomplete="off" value required/> </div> <div class="am-form-group"> <label for="doc-vld-desc-2">用户邮箱: </label> <input type="text" name="email" autocomplete="off" value required/> </div> <div class="am-form-group"> <label for="doc-vld-desc-2">用户最后登陆时间:</label> <input type="text" disabled='true' name="loginTime" value required/> </div> <input class="am-btn am-btn-primary" type="submit" name="getresult" value="更新" /> </fieldset> </form>
使用这种方式便可对form进行异步提交,提交以后我发现后台反回了以下错误ajax
个人后台的java代码以下,采用了spring mvc 的restful风格进行编写的spring
@RequestMapping(value = "/update",method = RequestMethod.POST) public String updateUser(HttpServletRequest request,HttpServletResponse response) { response.addHeader("Access-Control-Allow-Origin", "*"); /* 获取前台传送的参数 */ String id = request.getParameter("id"); ...... /* 组装user */ User user = new User(); user.setId(Integer.parseInt(id)); ....... boolean updateResult = service.update(user); logger.debug("UserController+updateUser()-------->" + updateResult); return String.valueOf(updateResult); }
我发现不能返回我想要的字符串,因而使用@ResponseBody来返回数据(@responsebody表示该方法的返回结果直接写入HTTP response body中通常在异步获取数据时使用,在使用@RequestMapping后,返回值一般解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。好比异步获取json数据,加上@responsebody后,会直接返回json数据)因而返回结果成功。
@Responsebody原理
该注解用于将Controller的方法返回的对象,经过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。注意到使用@ResponseBody将会跳过视图处理部分,调用合适的HttpMessageConverter,将返回值写入输出流。json