views:

70

answers:

2

hello all, my code is like this:

<%
ArrayList<Item> itemList = new ArrayList<Item>();
itemList = projr.getObjects(projectID);
if (itemList.size() != 0) {
%>

<script type="text/javascript">
window.onload = function() {
for(var i = 0;i < <%=itemList.size()%>;i++){
    var azimuth=0;
    azimuth = <%=itemList.get(i).getAzimuth()%>;
</script>

<%
}
%>

basically as you can see, due to certain reasons, i need to do the for loop within javascript. However, I cannot use the variable 'i' declared in javascript within the jsp<%=%> tag. Hence, I was wondering if there could be any work arounds.

I've tried to store 'i' as a cookie and try to retrieve it in the jsp by doing smth like:

azimuth = <%=itemList.get(Integer.parseInt((request.getCookies())[0].getValue())).getAzimuth()%>;

However, sadly this doesn't work. Also, I've thought of using hidden input fields to store 'i' but I don't think it would work as even if a did a request.getParameter(input name), i would not get anything as I have not submitted anything. Am I correct to say that?

I would appreciate if any of you kind souls could help me out here =]

+1  A: 

You should execute the for loop in JSP/Java, not in JavaScript.

<%
ArrayList<Item> itemList = new ArrayList<Item>();
itemList = projr.getObjects(projectID);
if (itemList.size() != 0) {
%>

<script type="text/javascript">
window.onload = function() {
    <%
    for(int i = 0; i itemList.size(); i++) {
    %>
    var azimuth=0;
    azimuth = <%= itemList.get(i).getAzimuth()%>; // Note: this will overwrite the original value on every loop. Not sure what you want, I've just make the code to work.
    <%
    }
    %>
</script>

<%
}
%>

That said, using scriptlets is an extremely poor practice. I recommend to have a look at JSTL/EL or eventually Ajax+JSON.

Here's a JSTL/EL targeted example:

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

<c:if test="${not empty itemList}">
    <script>
        window.onload = function() {
             <c:forEach items="${itemList}" var="item">
                 var azimuth = 0;
                 azimuth = ${item.azimuth};
             </c:forEach>
        }
    </script>
</c:if>

Once again, you're overwriting azimuth in every iteration, but you're also doing that in the original question, so you probably know what you're doing. I'm just wondering.

BalusC
A: 

What about this:

<%
ArrayList<Item> itemList = new ArrayList<Item>();
itemList = projr.getObjects(projectID);
if (itemList.size() != 0) {
%>

<script type="text/javascript">
window.onload = function() {
<%for(Item i : itemList){%>
    var azimuth=0;
    azimuth = <%=i.getAzimuth()%>;
<%}%>
</script>

<%
}
%>
Jaydeep