如何使用AJAX将ActionErrors,FieldErrors作为JSON返回并在表单上显示错误 [英] How to return ActionErrors, FieldErrors as JSON and display errors on the form using AJAX
问题描述
我想知道是否有人可以对以下内容提出任何想法.
I am wondering if anybody can throw any ideas on the following.
使用 validate()
方法获得一个Action类,当验证失败时,返回带有 actionErrors
, fieldErrors
的输入JSP.
Got an Action class with validate()
method returning input JSP with actionErrors
, fieldErrors
when validations fail.
我只想获取验证错误(JSON数据?),并在现有页面上显示错误并突出显示字段,而不是用新的响应JSP刷新整个JSP.
I would like to get only the validation errors (JSON data?) and display the errors on the existing page and highlight the fields, rather than refreshing whole JSP with new response JSP.
JQuery用于客户端,Struts2作为MVC框架,Liferay作为Portal服务器.
JQuery is used on client side, Struts2 as MVC framework, Liferay as Portal server.
以下是我尝试的代码:
public void validate() {
setActionErrors(validateData(this));
}
struts.xml:
<result-types>
<result-type name="json" class="org.apache.struts2.json.JSONResult"/>
</result-types>
<interceptors>
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
</interceptors>
<action name="saveDataAsync" class="MyActionClass" method="addDataAsync">
<result name="success">/jsp/addDataAsync.jsp</result>
<result name="input" type="json">
</result>
</action>
JSP:
<portlet:actionURL name="saveData" var="saveDataActionURL">
<portlet:param name="struts.portlet.action" value="/saveDataAsync"/>
</portlet:actionURL>
JS:
jQuery.ajax({
type: 'POST',
url: "<%=saveDataActionURL%>",
data: jQuery("#form").serialize(),
dataType: 'json',
success: function(data) {
alert("data" + data);
}
});
在执行validate方法之后.即使有错误添加到错误列表并通过 setActionErrors()
方法进行设置,流程仍在执行操作类的默认方法.当拦截器和调用方法被调用时,我可以看到resultcode:作为"input"
和结果:作为"jsonresult"
.
After execution of validate method. the flow is executing default method of action class, even when there are errors added to errorlist and set through setActionErrors()
method. I could see resultcode : as "input"
and result: as "jsonresult"
when the interceptors and invoke methods get called.
我真的很感谢您在此问题上的帮助.
I really appreciate any help on this problem.
推荐答案
您可以将 INPUT
结果配置为 json
类型的操作,并使用 includeProperties
参数以指定生成的JSON.
You can configure INPUT
result to your action of type json
and use includeProperties
parameter to specify generated JSON.
<result name="input" type="json">
<param name="ignoreHierarchy">false</param>
<param name="includeProperties">^actionErrors\[\d+\],^fieldErrors\['\w+'\]\[\d+\]</param>
</result>
动作类应扩展 ActionSupport
,以便这些属性可用.
The action class should extend ActionSupport
, so these properties will be available.
这篇关于如何使用AJAX将ActionErrors,FieldErrors作为JSON返回并在表单上显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!