【发布时间】:2011-01-28 15:13:20
【问题描述】:
我在服务器端使用 Spring MVC,但在其中一个页面中,我决定使用 jQuery 创建 AJAX 验证,而不是默认的 Spring 验证。 一切都很好,除非我必须进行远程验证以检查数据库中是否已经存在“标题”。 对于 javascript,我有以下内容:
var validator = $("form").validate({
rules: {
title: {
minlength: 6,
required: true,
remote: {
url: location.href.substring(0,location.href.lastIndexOf('/'))+"/checkLocalArticleTitle.do",
type: "GET"
}
},
html: {
minlength: 50,
required: true
}
},
messages: {
title: {
required: "A title is required.",
remote: "This title already exists."
}
}
});
然后,我使用 Spring-Json 进行验证并给出响应:
@RequestMapping("/checkLocalArticleTitle.do")
public ModelAndView checkLocalArticleTitle(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Map model = new HashMap();
String result = "FALSE";
try{
String title = request.getParameter("title");
if(!EJBRequester.articleExists(title)){
result = "TRUE";
}
}catch(Exception e){
System.err.println("Exception: " + e.getMessage());
}
model.put("result",result);
return new ModelAndView("jsonView", model);
}
但是,这不起作用,并且永远不会验证“标题”字段。 我认为这样做的原因是我以以下方式返回答案:
{result:"TRUE"}
事实上,答案应该是:
{"TRUE"}
我不知道如何使用 ModelAndView 答案返回像这样的单个响应。
另一件不起作用的是“远程”验证的自定义消息:
messages: {
title: {
required: "A title is required.",
remote: "This title already exists."
}
},
所需的消息有效,但远程消息无效。 我环顾四周,但没有看到很多人同时使用 Spring 和 jQuery。至少,不要与 jQuery 远程验证和 Spring-Json 混合。 我会在这里得到一些帮助。
【问题讨论】:
-
没人知道答案吗?
标签: jquery json validation spring