Using Javascript within a JSP

nuclearfly

Limp Gawd
Joined
Aug 24, 2004
Messages
262
Hey guys, new to JSPs and JavaScript.

What I need to do, is gather a selection from a combobox on the JSP when the submit button is clicked, and use it as a parameter to a Java function, which is imported.

Something like this maybe?



Code:
<input type="submit" name="combobox" value="Continue" 
       onclick="bean.function( document.form.combobox.value )">

Let me know what you guys think. I think there are probably some errors in this, and I'm working on setting up the server to test it now.

 
What does your JavaScript code look like?

It may be easier to use the POST method and call a Java Servlet
 
That's it, up there, between the parenthesis. I'm just referring to the value the way you would in JS. I don't think it'll work like that. bean.session is a function within a java file which is imported earlier in the JSP.

Yeah, I thought about having it POST to another JSP or a servlet, but I was going to see if I could get it done on one page, since this is going to be forwarding on to another page anyway. (Which I can't edit, so I can't just POST it there)

 
As far as I am aware, what you are trying to do is quite illegal. You can't use javascript (client side) to invoke a method out of a server side Object.
 
AFAIK you can't do anything like that... you have to remember that Java will be interpreted server side, and by the time the page shows up in the browser, it's just HTML....
 
nuclearfly said:
Code:
<input type="submit" name="combobox" value="Continue" 
       onclick="bean.function( document.form.combobox.value )">
It would take an awful lot of hacking, but the great thing about JSP (and to a much lesser extent, Javascript) is that it's tremendously powerful (the tradeoff being that it can be quite daunting even for simple tasks).

So if you wanted to get something like that to work, here's roughly what you'd have to do:
  1. Make a servlet or a very simple JSP that reads a value (doing it via GET would be easiest, I think) and just calls your bean's function with that value.
  2. Make a Javascript object with the same name as your bean.
  3. Give this JS object a method with the same name and signature as the method in your bean.
  4. Have this method use XMLHttpRequest or something similar to pass that value to the simple JSP you made, just by passing it in the query string.
  5. Include this Javascript code in your page. Now when you hit the button, your new javascript function will pass that value to the server, your bean will get the call, and you can stay right there on the same page.

It's that simple. ;)
 
Good point about the client side verses server side, I guess I'll just have to put another intermediate page after this one.

Thanks for all the help guys.

 
Back
Top