文件开始下载时触发javascript事件-收到响应时
其目的是在服务器准备下载文件时显示等待微调器图标。在我的用例中,我生成一个大型报告,在调用浏览器的下载/另存为提示符之前,服务器端需要一些时间。我可以向等待微调器显示没有问题,但我很难找到清除它的方法 现行有关守则:文件开始下载时触发javascript事件-收到响应时,javascript,html,jsf,download,Javascript,Html,Jsf,Download,其目的是在服务器准备下载文件时显示等待微调器图标。在我的用例中,我生成一个大型报告,在调用浏览器的下载/另存为提示符之前,服务器端需要一些时间。我可以向等待微调器显示没有问题,但我很难找到清除它的方法 现行有关守则: <h:commandButton id="generate" value="Generate Report" type="submit" action="#{bean.generateReport()}" onclick="#{rich:component
<h:commandButton id="generate" value="Generate Report" type="submit"
action="#{bean.generateReport()}"
onclick="#{rich:component('waitIcon')}.start();"/>
<a4j:status id="waitIcon">
<f:facet name="start">
<h:graphicImage value="/images/ai.gif" alt="ai" />
</f:facet>
</a4j:status>
)
使用窗口.timeout
函数调用组件上的.stop()
。这在功能层面上是可行的,但由于生成时间在1-10秒之间波动很大,这使得指示器无法反映现实
有人对处理这件事有什么好主意吗 最简单的解决方案是将setTimeout设置为1秒,以检查是否收到响应。setTimeout将重复,直到清除为止
所以你可以做:
var responseReceived, hTimer = setTimeout( function() {
if( responseReceived ) {
// code to stop/hide spinner here
clearTimeout( hTimer );
}
}, 1000 );
// responseReceived is set when the response is received
或者,您需要的是编程术语中所谓的comet。对于您的需求,Ajax长轮询应该最适合您的需求。基本上,您可以向服务器打开一个ajax请求(这是异步的),当服务器响应时,回调函数可以执行您想要的任何操作。看看这些参考资料:
如果我理解正确,您的用户将在表单中填写一些数据,然后单击提交按钮将数据发布到服务器,服务器随后对其进行处理,并在一段时间后生成响应,触发“另存为…”对话框窗口。如果这是正确的,解决方案是创建一个隐藏的iframe,然后通过在表单上设置target属性,将服务器的响应重定向到该iframe,最后,挂接iframe的onload事件,一种方法是返回到同一页面,在该页面中有条件地呈现一段JS代码,从而启动实际下载
<h:form>
...
<h:commandButton value="submit" action="#{bean.prepareFileForDownload}" />
<h:outputScript rendered="#{bean.fileReadyForDownload}">
// Do here your thing to indicate start of download.
window.location = '#{bean.fileDownloadURL}';
</h:outputScript>
</h:form>
在downloadFile()中使用此文件
真正的问题在于何时收到响应:)comet链接中的iframe建议看起来是最有希望的,但是我相信我在尝试通过该iframe通过javascript/ajax启动下载时也会遇到类似的问题。将证明这一点并回答。。。我希望有一个更直接的解决办法。啊,我误解了你关于window.timeout的观点。在这种情况下,comet解决方案可能是你最好的答案。你的问题标题令人困惑。当文件下载完成时,您似乎对启动JS代码很感兴趣。你能修改一下吗?我真的很想在文件下载开始时触发JS代码(浏览器收到响应)。我希望显示微调器的事件增量来自发送的请求->接收的响应。通过onclick事件发送很容易。收到。。。并非如此:)
<h:form>
...
<input type="hidden" name="token" value="#{bean.token}" />
<h:commandButton value="submit" action="#{bean.downloadFile}" onclick="checkToken(this.form.token)" />
<h:outputScript>
function checkToken(token) {
var pollDownloadStart = setInterval(function() {
if (document.cookie.indexOf("download=" + token) > -1) {
document.cookie = "download=" + token + "; expires=" + new Date(0).toGMTString() + "; path=/";
clearInterval(pollDownloadStart);
// Do here your thing to indicate start of download.
}
}, 500);
}
</h:outputScript>
</h:form>
// Prepare download here.
// ...
// Once finished, set cookie and stream download to response.
Cookie cookie = new Cookie("download", token);
cookie.setPath("/");
response.addCookie(cookie);
// ...