0

I attempted to convert java array to js array. but it gives error as "k cannot be resolved to a variable".x.getrows returns array.

  <% MySQLAccess x=new MySQLAccess();%>
     <% String b[]=x.getRows();%>
     var message="<%out.print(b[0]);%>"
     console.log(message)   
     var data=new Array();
         <% for(int k=0;k<b.length ;k++) %>
         <%  {%>

          var temp=<%= b[k] %>
          data[<% =k %>]=temp;    
        <%}%>   
3
  • dont mix java and javascript like this .. i hope you're aware its really bad code. Commented Oct 30, 2013 at 12:03
  • isn't the space between the '%' char and the '=' in the line data[<% =k %>]=temp; an error? Commented Oct 30, 2013 at 12:04
  • I resolved it. then also same error Commented Oct 30, 2013 at 12:06

3 Answers 3

1

@user2815407 What you are receiving in your string array? May be something like [str1,str2,str3]. If so you can easily convert this string array into js array.

var values = [];
values = //Your_string_array
//Iterate through each value
$.each(values, function( index, value ) {
   console.log(value);
});

See this fiddle. This may not be optimal way to convert java to js array. Hope this will give you some idea. Let me know if this helps.

1

I advice not to use scriplets, but here's the solution to your problem :

 <% String b[] = new String[]{"10", "20", "30"};%>
            var message = "<%out.print(b[0]);%>"
            console.log(message)
            var data = new Array();
            <% for(int k=0;k<b.length;k++){%>
            var temp =<%=b[k]%>
            data[<%=k%>] = temp;
            <%}%>

The error was just un-necessary spaces.

0

My advice to fix this code: forget about it:

  • you should NEVER use scriptlets in JSPs
  • JS string literals need quotes around them, and escaped quotes and other escaped special chars inside
  • JSON is the tool you should use.

So, in your controller, use

request.setAttribute("jsArray", someJsonSerializer.toJson(javaArray));

And in your JSP:

var data = ${jsArray};
2
  • controller means my MysqlAccess java program. Commented Oct 30, 2013 at 12:42
  • No. The controller is the controller in the Model-View-Controller architecture. Read java-samples.com/showtutorial.php?tutorialid=350 for example. Commented Oct 30, 2013 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.