Ajax error struts2?

爱⌒轻易说出口 提交于 2019-12-06 12:47:43

You can configure result ERROR to return the rendered error page fragment to the Ajax response.

<result name="error">/error.jspx</result>

error.jspx:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%
    request.setAttribute("decorator", "none");
    response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
    response.setHeader("Pragma","no-cache"); //HTTP 1.0
    response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
<s:if test="hasActionErrors()">
       <s:actionerror />
</s:if>

Please check the following

In your struts.xml edit the following

<result name="success" type="json">
  <param name="ignoreHierarchy">false</param>
    <param name="includeProperties">
        actionErrors.*,
        actionMessages.*,
        fieldErrors.*
    </param>
</result>

And in your js code edit the below.

    var actionErrs= (data.actionErrors); // list of action errors
    var actionMsgs= (data.actionMessages); // list of action messages
    var actionFldErrs= (data.fieldErrors); // list of field errors

   var alertMessage="";
    var i=0;
    for(i=0;i<actionErrs.length; i++){
    alertMessage=alertMessage+" "+actionMessages[i];
    }

    alert(alertMessage);

Edit in your JSP instead of the following,

<s:if test="hasActionErrors()">
       <s:actionerror />
</s:if>

use

<div id="err"></div>

and add below line in you js code

document.getElementById("err").innerHTML=alertMessage;

to check the result name

if your method signature like below,

public String getJsonData(){
if(....){
return ERROR;
}
return SUCCESS
}

You can get the data in your js code as below,

var actionErrs= (data.actionErrors); // list of action errors
var actionMsgs= (data.actionMessages); // list of action messages
var actionFldErrs= (data.fieldErrors); // list of field errors

var resultName=(data.getJsonData); // get The method return value

var alertMessage="";
var i=0;
for(i=0;i<actionErrs.length; i++){
alertMessage=alertMessage+" "+actionMessages[i];
}

alert(alertMessage);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!