假设我有一个类似的 Java 函数
public int getNumber(){
}
它根据其逻辑返回一些值。我有一个 JS 文件,类似于
Tapestry.Validator.amountValidator = function(field, message) {
field.addValidator(function(value) {
if (value != null) {
// code here
}
}
});
};
现在我问自己是否可以在 JS 或 JQuery 中将值从 Java 函数传递到 JS 中的函数(值),如果可以,如何实现?
更新:正如 abalos 答案所建议的,Tap for myself 已经完成了 4 个阶段中的 3 个阶段。我提供了一个处理服务器端及其背后逻辑的函数。
@InjectComponent
private TextField amount;
@Inject
private FieldValidatorSource fieldValidatorSource;
public FieldValidator<?> getAmountValidator()
{
return fieldValidatorSource.createValidators(amount, "required,max=" + getBroj());
}
现在这里的 validator 是从函数 getBroj() 内部的逻辑中获取的,这是它所需要的最大数量。这在服务器端就像一个魅力。现在我在想,我没有的(使用我的逻辑)只是客户端,我可以通过更新 Tapestry 中的当前 Validation 类来实现它,该类将处理该类已知的此类请求。为此,我需要调用一个 js 文件,其中包含一个函数,该函数调用上面示例中的内容,但我不太确定如何将值从 getNumber() 函数传递到上面的 JS 函数。
最佳答案
您根本不需要 Jersey 或 DWR 或任何其他框架来调用 Tapestry 中的方法。您只需要正确地提出问题即可。
final private static String EVENT_NAME = "whateverEventNameYouWant";
@Inject
private ComponentResources resources;
@Inject
private JavaScriptSupport javaScriptSupport;
/** Method that will provide the value you want to pass to JS. */
@OnEvent(EVENT_NAME)
public JSONObject provideValue() {
JSONObject object = new JSONObject();
object.put("value", /* the value you want to pass to JS */);
// other values you may want to pass
return object;
}
void afterRender() {
// This creates an URL for the event you created. Requesting it will
// invoke any event handler methods for that event name.
Link link = resources.createEventLink(EVENT_NAME);
javaScriptSupport.addScript("var eventUrl = '%s';", link.); // the JavaScript variable name doesn't matter. You can choose any you want
}
然后,在 JavaScript 中,使用 eventUrl 变量中的 URL 执行 AJAX 请求。我将把这部分留给您从 jQuery 文档中找出答案。接收到的数据正是您将在事件处理程序方法中返回的 JSONObject 或 JSONArray。
关于java - 从 Java 函数向 JS/JQuery 函数分配/传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26547184/