Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Arrays in Javascript  RSS feed

 
S Zaidi
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a collection of codes (about 7 or 8) that I read from the database in the servlet. Although they are being read from a database and are supposedly dynamic, the fact of the matter is that they would not change for years. Hence I want to cache them on the client side in Javascript and use them to verify what a user enters as a code in a text field. Its probably a good idea to verify (say onBlur())if he has enetered the right code. Note we dont want this to be a dropdown but just a plain text field (as per the specs) where a usre enters a 4 digit code and we need to verify if the code exists in our array.
How can we pass this array from servlets to JSP and use it on Javascript?
Any help would be appreciated.
Thanks
[ February 17, 2005: Message edited by: S Zaidi ]
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66142
141
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The same way you create other HTML markup using template text. Remember anything that's not a JSP element just gets sent to the browser as is. So you can build up Javascript dynamically just as easily as you can build up HTML.

Generate the verification codes in a Javascript array and then a validation routine can use that data to check the user's entry.
[ February 17, 2005: Message edited by: Bear Bibeault ]
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Bear's post. Here is a little more detail on how to go about this.

From your servlet, put a string representation of the codes array into the HttpServletRequest object - something like this:

String[] codes;
String codesArrayString;
// insert here code to place all the elements of codes into codesArrayString
// in the format: "['xxx', 'yyy', 'zzz']"
request.setAttribute("codesArrayString", codesArrayString);

Then in the jsp, you can retrieve the codes from the HttpServletRequest object and put them in a javascript array something like this:

<SCRIPT type="text/javascript">
var codes = <%=(String) request.getAttribute("codesArrayString") %>;
</SCRIPT>
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!