[英]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. 我一直在尝试通过JSNI将值传递到Javascript方法中,但是它一直失败。
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. 我可以说JS方法是正确的,因为如果我将一个常量值替换为productId
,那么我将获得正确的输出。
What am I missing? 我想念什么?
JSNI does not allow using long
as input variable, see explanation here . JSNI不允许使用long
作为输入变量,请参见此处的说明。
You could try using double (or even int) instead, but make sure that your Javascript code supports it. 您可以尝试使用double(甚至是int),但要确保Javascript代码支持它。
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. 如果确实需要传递很长时间,则可以将其作为字符串传递,然后使用parseFloat进行转换。 It's explained in this post. 在这篇文章中对此进行了解释。
how-to-convert-a-string-to-long-in-javascript 如何对转换-A-字符串到长中的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. 如果您使用gwtquery,您将拥有不错的实用程序方法,从而避免在处理大多数琐碎的事情(例如调用js函数,构建或读取js属性)时不必处理JSNI。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.