问题
I've been trying to pass a value into a Javascript method through JSNI but it keeps on failing.
Is this method valid:
public static native JavaScriptObject getProductById(long pid) /*-{
var productId = pid;
var product = $wnd.products({id:productId}).first();
return product;
}-*/;
I can say that the JS method is correct, since if I put a constant value in place of productId
, I get the correct output.
What am I missing?
回答1:
JSNI does not allow using long
as input variable, see explanation here.
You could try using double (or even int) instead, but make sure that your Javascript code supports it.
public static native JavaScriptObject getProductById(double pid) /*-{
var productId = pid;
var product = $wnd.products({id:productId}).first();
return product;
}-*/;
回答2:
If you really need to pass it as a long then you could pass it as a string and then converted it using parseFloat. It's explained in this post.
how-to-convert-a-string-to-long-in-javascript
回答3:
If you use gwtquery, you will have nice utility methods to avoid having to deal with JSNI for most trivial things like calling a js function, or for building or reading js properties.
import static com.google.gwt.query.client.GQuery.*;
...
Properties prd = JsUtils.runJavascriptFunction(window, "products", $$("id: 12345"));
Properties ret = JsUtils.runJavascriptFunction(prd, "first");
System.out.println(ret.toJsonString());
来源:https://stackoverflow.com/questions/15494262/pass-value-from-gwt-to-javascript-via-jsni