开发者

Calling Javascript function from Java using JSObject

I'm just开发者_StackOverflow中文版 trying to call a Javascript function from Java using JSObject. I need the Javascript function to update an HTML text field. For this I need to know the element ID and the value.

I have tried this but it doesn't work. When trying to access from Javascript the values passed are empty.

So my question is how can I access those values from Javascript? I must be missing something.

If I declare objects of size 1 it will work, but I need to pass 2 values in objects array.

Thanks in advance.

//Java code
Object[] objects = new Object[2];
objects[0] = "elementId";
objects[1] = "elementValue";
window.call("updateElement",objects);

//Javascript code
function updateElement(array){
  alert(array[0]);
  alert(array[1]);
}


So I noticed that you are using an Object array in java and passing in string values. Have you tried using a String array?

String[] x = new String[2];
x[0] = "elementId";
x[1] = "elementValue";
window.call("updateElement", x);

give that a try and see if that works. my guess is that javascript isnt able to realize that object array being passed is a string array. though i am not 100% sure.


In your example you should see alert('e') and alert('l') show up because you're passing two arguments to 'updateElement'. You can always use the arguments object in javascript to inspect what you really received.

I suggest to always create the final argument list separately and last, so you don't have this problem. It's just a horrible design flaw that they didn't update the signature to JSObject.call(String, Object...) in Java 5, we would have much less headaches that way.

A cleaner solution would be:

// Java code
window.call("updateElement", new Object[] { "elementId", "elementValue" });

// Javascript code
function updateElement(elId, elVal){
    alert(elId);
    alert(elVal);
}

but if you really want to stick to receiving an array in JS:

String[] arr = new String[] { "elementId", "elementValue" };
window.call("updateElement", new Object[] { arr });


The way call works is that you pass in an array of the functions arguments. Here you have only one argument ( your array), so you need to call it like :

//Java code
Object[][] objects = new Object[][1];
objects[0]=new Object[2];
objects[0][0] = "elementId";
objects[0][1] = "elementValue";
window.call("updateElement",objects);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜