jQuery in Action, 3rd edition
The moose likes Servlets and the fly likes Pass Array from servlet program to JavaScript Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Pass Array from servlet program to JavaScript" Watch "Pass Array from servlet program to JavaScript" New topic

Pass Array from servlet program to JavaScript

Surasak Leenapongpanit
Ranch Hand

Joined: May 10, 2002
Posts: 341
I have a question. I write a Java Servlet program to read data from database. I store those data into an array. Then I want pass that array to JavaScript. I also have a select option. My JavaScript will do something according to my selection to display some information from my data array to the other(2nd) select option in the client side browser. That is I want show some information dynamically.
Can I pass an array from Java program to JavaScript? If yes, how?
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
The way to pass data from Java (servlet/JSP) to Javascript is to dynamically generate the JavaScript as if it "always knew" the data. For example

[ January 28, 2004: Message edited by: Frank Carver ]

Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Jayson Falkner
Ranch Hand

Joined: May 07, 2001
Posts: 57
I think Frank's suggestion is the only way to do this. It is important to realize there is no direct connection between objects kept in memory on your server and objects in the client's browser's memory (e.g. JavaScript variables). If you want to dynamically control JavaScript, you are stuck generating the script on your server and sending it off for use in the client's web browser.

Jayson Falkner<br />jayson@jspinsider.com<br />Author of <a href="http://www.jspbook.com" target="_blank" rel="nofollow">Servlets and JavaServer Pages; the J2EE Web Tier</a>
Ko Ko Naing
Ranch Hand

Joined: Jun 08, 2002
Posts: 3178
What about using hidden values in the HTML form and assign the java variables' values into them??? :roll:

Co-author of SCMAD Exam Guide, Author of JMADPlus
I agree. Here's the link: http://aspose.com/file-tools
subject: Pass Array from servlet program to JavaScript
It's not a secret anymore!