I want to pass a Java string variable to Javascript function which I am calling in Java code. Somehow the value of string remains as null. Is there any way to do this?
Here is some sample code
cb.set(CheckBox.ONCLICK,"displayCB(" + e.getFormName() + ",document.Profile.UniqueForm"+"_TestOpt)");
So in above line of code i am calling displayCB javascript function in generated Javascript code while my function for displayCB is like below:
sc.add("function displayCB(formname,field){"); sc.add("var str = formname + 'TestOption'"); ..
when I debug through firebug, I get str value as null
-
How are you passing it, using JSTL and response properties? Please show the code.Kaleb Brasee– Kaleb Brasee2009年12月09日 16:21:23 +00:00Commented Dec 9, 2009 at 16:21
-
Are you passing the value in a response from the javascript, such as a json response? Javascript won't understand Java, but it does understand strings.James Black– James Black2009年12月09日 16:23:05 +00:00Commented Dec 9, 2009 at 16:23
-
Is the Java running on the server or the client?Diodeus - James MacFarlane– Diodeus - James MacFarlane2009年12月09日 16:32:24 +00:00Commented Dec 9, 2009 at 16:32
2 Answers 2
try changing
cb.set(CheckBox.ONCLICK,"displayCB(" + e.getFormName() + ",document.Profile.UniqueForm"+"_TestOpt)");
to
cb.set(CheckBox.ONCLICK,"displayCB('" + e.getFormName() + "',document.Profile.UniqueForm"+"_TestOpt)");
The additional single quotes will make the script treat the value as a string literal instead of a variable name.
Comments
pass a Java string variable to Javascript function
Does this mean that:
You're using JSP (server-side) to render values that are passed to JavaScript code which is executed on the client-side. This is not really calling between Java and JavaScript, more like generating JavaScript code with Java.
You're really calling from Java to JavaScript, i.e using the JS runtime (Rhino?) in the JVM
Once you clarify this point, I'll try and help further. Also, please show the relevant code.
Update:
It seems like the only possible reason why str is null is because the formname parameter of yout JS function is null. The value passed for this parameter (in code generated by the JSP) is e.getFormName().