iJared
iJared

Reputation: 947

Combining JSP servlets and Javascript

I have been working with ASP.NET for a few years and am now working on a project using JSP, Struts, and Java so I am fairly new to this.

I have a for-loop in a JavaScript function that looks something like this:

<% int count=0; %>
for(i = 0; i < arrayCount; i++){
   jsArray[i] = <%= myBeanArrayList.get(count) %>;
   alert("i = " + i + "count = " + count);
   <% count++; %>
}

The count variable doesn't increment even if I use <% count = count + 1 %>. I don't understand why that piece of code doesn't do as I want inside the loop. Does anyone have any suggestions on how I can increment the count for the JSP Bean?

Upvotes: 3

Views: 3261

Answers (4)

gilly3
gilly3

Reputation: 91467

You are only looping on the client, not the server. The server code only gets executed once. So, for every iteration of the JavaScript loop, you are using the same value - myBeanArrayList.get(0). View source to look at the generated HTML code and that will probably help to clarify the problem.

Edit: Instead, use server-side code to build a JavaScript array literal. I don't really know JSP, and my Java is a little rusty, but wouldn't this work?

var jsArray = <%= new JSONArray(myBeanArrayList) %>;

Upvotes: 0

duffymo
duffymo

Reputation: 308733

No one should be using scriptlet code in JSPs. It's a late 90s idiom that has been found to be ugly, brittle, and hard to maintain. Model-2 MVC has swept the field.

You should concentrate on doing things on the server side. If you must write JSPs, use JSTL.

I think the current best practice is to use HTML, CSS, and JavaScript. Get data from services on the server side using HTTP GET/POST or AJAX calls.

Upvotes: 1

Mike C
Mike C

Reputation: 3117

I kind of agree with b1naryj, but you could try doing the looping in the jsp, and just write the array assignments in javascript, something like:

<% 
for(i = 0; i < arrayCount; i++){
   %>jsArray[<%i%>] = <%= myBeanArrayList.get(i) %>;
<%}%>

It is ugly, tho...

Upvotes: 1

user800014
user800014

Reputation:

That's because you are mixing things.

  1. Your loop is in javascript and the variable count doesn't exists there (beacuse it's java)
  2. You incremented count once, just in <% count++ %>

So if you change to use the loop inside java, the count can work just fine. For example:

<% for( int i = 0; i < ???; i++ ) { %>
 alert('<%= i %>');
<% } %>

But it's better separate your javascript from JSP. This can be a pain to mantain.

Upvotes: 2

Related Questions