Vivek
Vivek

Reputation: 1461

Struts object accessing in JS

I have a bean and want to iterate through the values and store it in an array.

My form bean name is keywords and the element to be accessed is keywordList, so in my JS when I alert("${keywords.keywordList}");

I get [com.test.bean.Keyword@10, com.test.bean.Keyword@f, com.test.bean.Keyword@e], but I want the values and assign them to a var, how can I do this?

Upvotes: 2

Views: 3798

Answers (4)

Saurabh
Saurabh

Reputation: 1406

This is what I have done to solve this issue on JSP page

< %@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<script type="text/javascript">

var keyWordsArray=new Array();

var rowCounter=0;

<c:forEach items="${keywords.keywordList}" var="keyWords">

    var fieldObj=new Object();

    fieldObj.value='<c:out value="${keyWords}"/>'

    keyWordsArray[rowCounter]=fieldObj;

    rowCounter++;

</c:forEach>

</script>

</code>

Now you can access keWordArray in Javascript.

Upvotes: 1

Vivek
Vivek

Reputation: 1461

Here is how I solved my problem

<script>
    var i = 0;
    var collection = new Array(); 
    </script>

And since I was using logic:iterator and displaying the values in the table, I added

<script>
   collection[i++] = "${keyword.name}";
</script>

Now when I alert collection, all the words are in the array. Which is exactly what I need.

Upvotes: 1

James.Xu
James.Xu

Reputation: 8295

javascript and java are two different languages, you can not assume that you pass the keywords.keywordList in java and get the corresponding objects in javascript, you need to iterate the keywordlist in java and create the corresponding javascript objects manually.

update: some pseudocode

out.print("var keywordsInJS = []")
for (String keyword : keywordList) {
    out.print("var keyword = '" + keyword + "';");
    out.print("keywordsInJS.push(keyword);");
}

// now you can use keywordsInJS in js.

Upvotes: 1

Random
Random

Reputation: 1125

In my experience JS and Java doesn't interact well...

I suggest you to use HTML as a middle term for them to interact. Like, for example, displaying the contents of the list in invisible text in html (with iterator and the property indexed you can have different names for each text), then you can get them in JS.

You should also keep the length of the list so when you iterate in JS you know when to stop.

I know this far from a perfect solution and far from something remotely nice to do. But I know no better way to do it :(

Hope there is one, so I can also use it :)

Upvotes: -1

Related Questions