如何使用 Ajax 不闪烁地更新 GraphicImage?

How Can I Use Ajax To Update A GraphicImage Without Blinking?

请看下面的表格。特别要注意 ajax 和 graphicImage 元素。 ajax 元素嵌入在 selectOneMenu 中。当菜单选择改变时,图像相应地更新。更新有时会导致 "blink"(旧图像消失,表格调整大小(缩小),新图像出现,表格恢复到原始大小)。我猜测不闪烁(闪烁)是由从 url(网络上其他地方的服务器)获取新图像的速度(或缺乏速度)造成的。如果没有在本地缓存所有图像,有没有办法解决这个问题?导致旧图像保留在原位直到新图像准备好?至少防止表单调整大小?

<h:form rendered="#{orderController.addingNew}" styleClass="demo">
    <fieldset>
        <legend>New Order</legend>

        <h:panelGrid columns="2">
            <h:outputText value="Patient"></h:outputText>
            <h:selectOneMenu validatorMessage="required" value="#{orderController.patientId}"  onchange="submit()">
                <f:selectItems value="#{orderController.patients}" />
            </h:selectOneMenu>

            <h:outputText value="Product"></h:outputText>
            <h:selectOneMenu value="#{orderController.productId}">
                <f:selectItems value="#{orderController.products}" var="product" itemValue="#{product.id}" itemLabel="#{product.name}" />
                <f:ajax render="productImage" listener="#{orderController.productSelectionChanged}"/>
            </h:selectOneMenu>

            <h:graphicImage url="#{orderController.productImageUrl}" id="productImage"/>
        </h:panelGrid>

        <h:panelGroup>
            <h:commandButton value="Save" action="#{orderController.save}" accesskey="s" styleClass="demo"/>
            <h:commandButton value="Cancel" action="#{orderController.cancel}" accesskey="c" immediate="true" styleClass="demo"/>
        </h:panelGroup>
    </fieldset>
    <h:outputText value="&#160;" />
</h:form>

您可以将 onevent 属性绑定到您的 ajax 标签:

<f:ajax render="productImage" listener="#{orderController.productSelectionChanged}" 
    onevent="ajaxEventListener"/>

然后,只要 ajax 过程的某个阶段发生,您就会收到通知。您可能有兴趣使用 jQuery:

实现类似的功能
function ajaxEventListener(data) {
    var status = data.status; // Can be "begin", "complete" or "success".
    var source = data.source; // The parent HTML DOM element.
    //Give your form an id in order to access the image in JS
    var $image = $(document.getElementById("yourFormId:productImage"));  //Grab your image

    switch (status) {
        case "begin": // Before the ajax request is sent.
            // Fade out your image
            $image.fadeOut( "slow" );
            break;

        case "success": // After update of HTML DOM based on ajax response.
            // You've got the url properly updated, start fading in the image again
            $image.fadeIn( "slow" );
            break;
    }
}

为了缩短加载时间,您应该阅读一些有关如何在 Web 浏览器中缓存资源的文章。不过,这不是 JSF 特有的,您可以这样做 with a web filter.

另请参阅: