简体   繁体   中英

Pass value from GWT to Javascript via JSNI

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?

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;
}-*/;

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

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM