Mehmood Memon
Mehmood Memon

Reputation: 1139

Struts 2 action not returning desired result to Jquery Ajax call

I am calling an action from jQuery Ajax with the following code and it returns me complete code of JSP page. All I need is the array list that is defined in the action class.

dashboard.js

$.ajax({
 url : 'ELD/getAllDivisions',
 type : 'POST',
 dataType: 'text/javascript',
 success : function(data) {
   alert("success");
   var response = data;
   alert(response);
  });

DivisionAction.java

@Autowired
private DivisionService divisionService;

private List<DivisionModel> divisionList = new ArrayList<DivisionModel>();

public String getAllDivisions() {
    divisionList = divisionService.getAllDivisions();
    return SUCCESS;
}

struts.xml

<constant name="struts.devMode" value="true" />
<package name="DIVISION" namespace="/" extends="struts-default">
    <action name="getAllDivisions" method="getAllDivisions" class="foo.bar.DivisionAction">
        <result name="success">/jsp/users/AdminDashboard.jsp</result>
    </action> 

Response enter image description here

All I need is the array list being returned from the action class.

Upvotes: 3

Views: 2527

Answers (1)

Andrea Ligios
Andrea Ligios

Reputation: 50203

You have two ways:

Old (unnecessarily complex) way

Return a JSP, inside the JSP iterate your list and do whatever you need: create a JSON array, or write HTML elements (eg. <option> elements), etc... for example:

<action name="getAllDivisions" method="getAllDivisions" class="foo.bar.DivisionAction">
    <result name="success">/jsp/users/allDivisions.jsp</result>
</action> 

allDivisions.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
[
<s:iterator value="divisionList" status="ctr">
    {         
       "id"        : "<s:property value='modelId'   />", 
       "modelName" : "<s:property value='modelName' />"
    }
    <s:if test="%{#ctr.count < divisionList.size}"> , </s:if>
</s:iterator>
]

New (right) way

Use the JSON plugin, return a JSON result specifying your List as the root object (read more):

<package name="DIVISION" namespace="/" extends="json-default">

    <action name="getAllDivisions" method="getAllDivisions" class="foo.bar.DivisionAction">
        <result name="success" type="json>
            <param name="root"> divisionList </param>
        </result>
    </action> 

Upvotes: 1

Related Questions