user3542411
user3542411

Reputation: 33

How to use ajax response list as struts2 iterator value?

I am using following ajax function :

 $.ajax({
       url: "userhomeonload",
       contentType: 'application/json',
       type: 'POST',
      datatype:'json', 
       async: true,
       success: function (res) {
                 alert(res[i].name+" "+res[i].rollNo);
    }  });

I am getting correct result in alert box. Now I want to use the list returned by this ajax in struts iterator as follows :

<s:iterator value="list">
   <div>
     <s:property value='name'></s:property>
     <s:property value="rollNo"></s:property>
   </div>
</s:iterator> 

But nothing is getting displayed on screen. Can anyone tell me how can I do so?

Upvotes: 3

Views: 4319

Answers (2)

saurabh goyal
saurabh goyal

Reputation: 1744

Actually what is happening behind the scene is after your ajax call you are only getting the JSON object but the the value of "list"

<s:iterator value="list">

is not mapped by the OGNL from the valuestack to the result page , for this approach to work in your case you have to set the property using JS.

As Andrea correctly explained if you return your result as a JSP all the property of your action object will be mapped by OGNL to the respective UI tags.

Upvotes: 0

Andrea Ligios
Andrea Ligios

Reputation: 50203

@AndreaLigios please explain 2nd type of result i.e. JSP snippet.I don't know how to use JSP snippet as ajax response.

Main.jsp (complete)

<%@ taglib prefix="s" uri="struts-tags.tld" %>
<html>
    <head>
        <script>
            $(function(){   
                $('#loader').on("keypress click", function(e) {
                    $.ajax({
                        url: "<s:url action='ajaxAction'/>",
                    }).done(function(result) {
                        $("#target").html(result);
                    });
                });
            });
        </script>   
    </head>
    <body>
        <input type="button" id="loader" />
        <div id="target"></div>
    <body>
</html>

Struts.xml (relevant)

<action name="ajaxAction" class="foo.bar.AjaxAction">
    <result>Snippet.jsp</result>
</action>

AjaxAction (relevant)

private String testString;
/* Getter and Setter */

public String execute(){
   testString = "I'm loaded with AJAX";
   return SUCCESS;
}

Snippet.jsp (complete)

<%@ taglib prefix="s" uri="struts-tags.tld" %>

<!-- This is the result page. You can use Struts tags here, 
the generated HTML will be appended to the target div. -->

TestString: <s:property value="testString" />

Output:

<body>
    <input type="button" id="loader" />
    <div id="target">TestString: I'm loaded with AJAX</div>
<body>

Upvotes: 1

Related Questions