几天来,我一直在尝试使 Struts2 AJAX 验证工作,但我无法解决最后一个问题。我正在使用 struts2jquery 插件异步提交我的表单:
<div id="result"></div>
<s:form action="RegisterUser" theme="xhtml" method="post">
<s:textfield key="firstname" label="First name" size="35"
required="true" />
<s:textfield key="lastname" label="Last name" size="35"
required="true" />
<s:textfield key="address" label="Address" size="35"
required="true" />
<s:textfield key="phone" label="Phone number" size="35" />
<s:textfield key="username" label="Username" size="35"
required="true" />
<s:password key="password" label="Password" size="35"
required="true" />
<s:textfield key="email" label="E-mail address" size="35"
required="true" />
<sj:submit key="Inregistrare" targets="result" align="right"
button="true" validate="true" onSuccessTopics="notifyRegistration" />
</s:form>
我已经包含了所需的脚本:
<script type="text/javascript" src="./js/registerScript.js"></script>
<!-- This files are needed for AJAX Validation of XHTML Forms -->
<script src="${pageContext.request.contextPath}/struts/utils.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/struts/xhtml/validation.js"
type="text/javascript"></script>
和标签:
<sj:head jqueryui="true" />
onSuccess 处理程序:
$(document).ready(function(){
$.subscribe('notifyRegistration', function(event,data) {
var registrationStatus = event.originalEvent.data.registrationStatus;
if(registrationStatus == 'SUCCESS'){
alert('Contul dumneavoastra a fost creat cu success!');
window.location.href = "./index.html";
} else {
alert('Contul dumneavoastra nu a putut fi creat. Va rugam incercati din nou.');
}
});
});
我的配置如下所示:
<action name="RegisterUser" class="actions.Register" method="execute">
<interceptor-ref name="jsonValidationWorkflowStack"/>
<result name="input">/pages/Register.jsp</result>
<result type="json"/>
</action>
还有我的动作类的执行方法:
public String execute() throws Exception {
if (isInvalid(getUsername()) || isInvalid(getPassword())
|| isInvalid(getEmail())) {
registrationStatus = REGISTRATION_ERROR;
}
if (registerUser()) {
registrationStatus = REGISTRATION_SUCCESS;
return SUCCESS;
}else {
registrationStatus = REGISTRATION_ERROR;
}
return SUCCESS;
}
该registerUser()
方法将实际插入到数据库中。验证 XML 称为Register-Validation.xml
. 验证工作正常 - 如果某些字段未填写,它会显示错误标签而不刷新页面。我的问题是,即使操作返回SUCCESS
或ERROR
,浏览器也会显示它在另一个页面上发回的 JSON,../Register.action。我不知道为什么它不进入我的onSuccess
处理程序。我已经在其他表单上成功使用了 AJAX,这里唯一的区别是我使用了验证 xml 和jsonValidationWorkflowStack
拦截器。为什么会发生这种情况,如何避免被重定向?为什么请求没有到达onSuccess
处理程序?