在调用 f:ajax 侦听器之前和之后执行 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24912335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:34:22  来源:igfitidea点击:

Execute JavaScript before and after the f:ajax listener is invoked

javascriptajaxjsf-2.2

提问by Karl Richter

It there an easy way to invoke a JavaScript action before and after the invocation of an <f:ajax listener>, e.g. I'd like to invoke window.alert("pre")beforeand window.alert("post")afteronChangeis invoked in the backing bean ACtrl:

它有一种简单的方法可以在调用 an 之前和之后调用 JavaScript 操作<f:ajax listener>,例如,我想在支持 bean 中调用window.alert("pre")之前window.alert("post")之后onChange调用ACtrl

<h:form>
    <h:inputText id="anId" value="#{cityCtrl.dbHost}">
        <f:ajax event="change" listener="#{aCtrl.onChange}" execute="@all"/>
    </h:inputText>
</h:form>
@ManagedBean
public class ACtrlimplements Serializable {
    public void onChange(AjaxBehaviorEvent event) {
        System.out.println("something changed");
    }
}

Adding multiple f:ajaxelements doesn't seem to work (maybe it should?!), e.g. in

添加多个f:ajax元素似乎不起作用(也许应该?!),例如在

<h:form>
    <h:inputText id="anId" value="#{cityCtrl.dbHost}">
        <f:ajax event="change" listener="#{aCtrl.toggle}" execute="@all"/>
        <f:ajax event="change" listener="#{aCtrl.onChange}" execute="@all"/>
        <f:ajax event="change" listener="#{aCtrl.toggle}" execute="@all"/>
    </h:inputText>
</h:form>
@ManagedBean
public class ACtrlimplements Serializable {
    public void onChange(AjaxBehaviorEvent event) {
        System.out.println("something changed");
    }

    public void toggle(AjaxBehaviorEvent event) {
        System.out.println("blah");
    }
}

only ACtrl.onChangeis invoked.

ACtrl.onChange被调用。

回答by BalusC

Use oneventattribute. It must point to a callback function reference (so don't include parentheses!):

使用onevent属性。它必须指向回调函数引用(所以不要包含括号!):

<f:ajax ... onevent="functionName" />

Whereby the actual callback function look like this (JSF will provide the argument all by itself):

因此实际的回调函数看起来像这样(JSF 将自己提供参数):

function functionName(data) {
    var status = data.status; // Can be "begin", "complete" or "success".
    var source = data.source; // The parent HTML DOM element.

    switch (status) {
        case "begin": // Before the ajax request is sent.
            // ...
            break;

        case "complete": // After the ajax response is arrived.
            // ...
            break;

        case "success": // After update of HTML DOM based on ajax response.
            // ...
            break;
    }
}

See also:

也可以看看: