This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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 ~ 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 /><br />Author of <a href="" 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
It is sorta covered in the JavaRanch Style Guide.
subject: Pass Array from servlet program to JavaScript
Similar Threads
JSP Combobox and Java Class
problem in selecting second arraylist from mysql database
Cascading Select statements using jQuery
Problem with AJAX and Struts
how to create JSON in javascript and get length of json