How do I pass some servlet variable to javascript?
Created May 7, 2012
out.println("<scriptlanguage="JavaScript" >"); out.println("<!-- hide from old browser...");I have an array in servlet that need to be copied to a new array in the javascript, how do I do that?
-----------------Normally, the result of servlet is an HTML page, which might contain JavaScript.
So you can not copy contents of servlet variable to javascript variable directly like in following code
The following code is actually creating javascript code which is then executed at client browser.
for(int i=0; i<strAlpha.length;i++){
letterArray[i]=strAlpha[i];
}
Servlets are executed at server while javascript is executed at client browser.
out.print("var letterArray = new Array(");
Boolean isFirst = true;
//Iterator through Array
for (int i=0; i < strAlpha.length; i++){
if (!isFirst){
out.print(","); <== Semi colon added
}
isFirst = false;
out.print("'" + strAlpha[i] + "'"); <== Single quote and Semi colon added
}
out.println(");");
If you see HTML source code, you will see following lines :
var letterArray = new Array('A','B','C','D','E','F','G','H','I');
Shirish