|
There are two methods to pass parameters from Java to JavaScript: eval() and call(). If you are using eval(), then you must call as many number functions as the number of parameters you are using. This can be time consuming. If you are using call(), however, you can save execution time.
Here are the key advantages to using call():
- Passing multiple parameters within a single statement
- Passing a variety of data types at once. (for example integers, char, character strings etc.,)
Below is the code sample that illustrates how to use call() to pass a number of parameters with different data types.
Note: Set your CLASSPATH to point to JSObject.class apart from the default settings to compile the java code.
HTML FILE TO TEST THE APPLET
<html>
<head>
<script>
function extractArray(var1, var2, var3)
{
alert ("Java returned string : " + var1);
alert ("Java returned int : " + var2);
alert ("Java returned char : " + var3);
}
</script>
</head>
<body>
<center>
<h3>PASSING PARAMETERS FROM
JAVA TO JAVASCRIPT</h3>
This example demonstrates
java applet passing a set of arguments to
Javascript.
Java passes a string, integer and
char to javascript on click of the
button. This
is only an illustration not a complete example.
<form>
<input type=button value=click
onClick=document.myApplet.create()>
</form>
<applet name=myApplet
code=array MAYSCRIPT></applet>
</body>
</center>
</html>
ARRAY.JAVA
import netscape.javascript.JSObject;
import java.lang.*;
import java.applet.*;
import java.awt.Graphics;
public class array extends Applet{
String testStr;
Integer testInt; /*integer */
Character testChar; /*character*/
JSObject win;
public void init(){
win = JSObject.getWindow(this);
}
void create(){
Object testArray[];
/*array to hold int, char and string*/
testArray = new Object[3];
testStr = new String("Test string");
testInt = new Integer(1);
testChar = new Character('a');
testArray[0] = testStr;
/*assign array elements*/
testArray[1] = testInt;
testArray[2] = testChar;
win.call("extractArray", testArray);
/*pass the arguments to JS*/
}
public void paint(Graphics g){
g.drawString("Here's an Applet which will " +
"deliver an array of Objects to " +
"Javascript on clicking the button", 50, 25);
}
}
|