我试图在提交表单后显示成功消息。我使用 link 中的 jQuery 表单插件
并且提交工作正常。就像这样:
$('#emailForm').ajaxForm();
现在我想在提交按钮下添加成功消息,因此我在下面添加了一个 div :
<input name="submit" type="submit" value="#springMessage('action.save')" />
<div id="emailSuccessMessage">
</div>
并对 jQuery 代码添加一些更改:
var options = {
target: '#emailSuccessMessage',
success: showResponse
};
$('#emailForm').ajaxForm(options);
function showResponse(responseText, statusText) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
我的 Controller 方法是:
@RequestMapping(value = "/password", method = RequestMethod.POST)
public String changePassword(@Valid @ModelAttribute("editPassword") EditPasswordForm editPasswordForm, BindingResult result) {
if (result.hasErrors()) {
return "editAccount";
}
userService.changePassword(editPasswordForm);
return "editAccount";
}
现在,当我尝试提交时,它可以工作,但没有显示警报(我添加了一个警报只是为了测试)。 showResponse 方法如何工作?我是 jQuery 新手,我想知道如何实现我的目标。我应该在哪里设置responseText?
谢谢
大卫
最佳答案
如果您将 ajax 与 Spring MVC 一起使用,您需要确保您的响应位于响应正文中,以便添加 @ResponseBody
注释
所以你的代码应该是这样的:
@RequestMapping(value = "/password", method = RequestMethod.POST)
@ResponseBody
public String changePassword(@Valid @ModelAttribute("editPassword") EditPasswordForm editPasswordForm, BindingResult result) {
if (result.hasErrors()) {
return "editAccount";
}
userService.changePassword(editPasswordForm);
return "editAccount";
}
您可以在 Spring MVC 引用指南中阅读更多相关内容: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody
关于jquery - 使用 jQuery 表单插件和 Spring MVC 提交表单后的成功消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6116523/