如何使用 Ajax 在不眨眼的情况下更新图形图像?



请看下面的表格。特别是,请注意 ajax 和 graphicImage 元素。ajax 元素嵌入在 selectOneMenu 中。当菜单选择更改时,图像会相应更新。更新有时会导致"闪烁"(旧图像消失,表单调整大小(缩小(,出现新图像,表单恢复为原始大小(。我猜测不眨眼(眨眼(是由于从 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的,而是您可以使用Web过滤器执行的操作。

另请参阅:

  • 在调用 f:ajax 侦听器之前和之后执行 JavaScript
  • 如何使用jQuery选择JSF组件?
  • http://api.jquery.com/fadeout/
  • http://api.jquery.com/fadeIn/

最新更新