Reputation: 1
I want to access the jsp array in Javascript. How it is possible?
JSpCode
<%!
String s[];
%>
<%
List l=(List)request.getAttribute("listResource");
System.out.println("The Elements In List::"+l);
if(l!=null)
{
System.out.println("The Size of List::"+l.size());
int siz=l.size();
Iterator itr=l.iterator();
while(itr.hasNext())
{
s=new String[siz];
int i=0;
s[i]=itr.next().toString();
System.out.println("The Elments are:"+s[i]);
i++;
}
}
%>
JavaScriptCode
function verify_details()
{
var resourceId=document.getElementById("res").value;
var rid=new Array();
rid=<%=s%>
alert(rid[0]);
}
I tried like this but I am not getting the values.
Upvotes: 0
Views: 2546
Reputation: 691655
JSP code is executed at server side, and generates text. Some of this text happens to be JavaScript code. JavaScript code is executed at client side, where the Java array doesn't exist anymore as a data structure.
When you write
rid=<%=s%>
You're asking to generate the following String : "rid=" + s.toString()
s
being a String array, the generated Javascript code will thus look like this :
rid=[Ljava.lang.String;@1242719c
And this is obviously not valid JavaScript code.
JavaScript code, when you're generating it with a JSP, is not any different from HTML code. If you want to generate the code rid = ['a', 'b', 'c'];
from a String Java array containing "a", "b" and "c", you need to iterate through the Java array and output a single quote followed by the current String followed by a single quote followed by a comma. Additionnally, you should escape each string to transform a quote character into \', a newline character into \n, etc. Use StringEscapeUtils.escapeJavaScript
from commons-lang to do that.
Upvotes: 2