概念
要在响应完成后在 java 代码中指定要运行的 JS 脚本 PrimeFaces 提供了带有函数 execute(String script) 的 RequestContext 实用程序 - 在 ajax 请求完成或页面加载后执行脚本。
假定存根的问题
让我们看看你的存根:
public void onPrimaryQueryDataSourceChanged() {
// ** Block UI **
// To show blockUI you may write the following:
RequestContext.getCurrentInstance().execute("PF('myBlockUI').show();");
// Note that even it is called "execute"
// script "PF('myBlockUI').show();" will be executed AFTER RESPONSE COMPLETE.
// So here you need to return.
// Then the response with included JS script to show blockUI will be send.
// Then client retrieves the response and runs your JS script.
// Then JS script shows blockUI.
// So the remaining code below is misplaced.
try {
// Run query, get results, and populate dropdown
} catch (SQLException e) {
e.printStackTrace();
} finally {
// ** Unblock UI **
}
解决方案
Ajax 具有适合您的情况的基本技术。您可以使用:
具体解决方案
只需混合来自 PrimeFaces Showcase 的示例:
http://www.primefaces.org/showcase/ui/ajax/dropdown.xhtml
http://www.primefaces.org/showcase/ui/misc/blockUI.xhtml
所以你可以这样写:
<h:panelGrid id="panelGridId" columns="2" cellpadding="5">
<p:outputLabel for="country" value="Country: " />
<p:selectOneMenu id="country" value="#{dropdownView.country}">
<p:ajax event="change" listener="#{dropdownView.onCountryChange}"
update="city" onstart="PF('myBlockUI').show()"
oncomplete="PF('myBlockUI').hide()" />
<f:selectItem itemLabel="Select Country" itemValue=""
noSelectionOption="true" />
<f:selectItems value="#{dropdownView.countries}" />
</p:selectOneMenu>
<p:outputLabel for="city" value="City: " />
<p:selectOneMenu id="city" value="#{dropdownView.city}">
<f:selectItem itemLabel="Select City" itemValue=""
noSelectionOption="true" />
<f:selectItems value="#{dropdownView.cities}" />
</p:selectOneMenu>
<p:blockUI block="panelGridId" widgetVar="myBlockUI" />
</h:panelGrid>
onCountryChange 的位置 - 为城市下拉列表填充 cities 的函数。
这种行为很常见,因此 PrimeFaces 提供了显示带有封装的 onstart 和 oncomplete scipts 的 blockUI 的声明方式:
<p:blockUI block="panelGridId" trigger="country" />
其中trigger 是组件的 id 列表,ajax 请求会触发要显示的 blockUI。