Pass value from GWT to Javascript via JSNI

天涯浪子 提交于 2020-01-25 12:04:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!