当url生成PDF输出时,Iframe onload不工作

iframe onload not working when url generates pdf ouput

本文关键字:Iframe onload 工作 url 生成 PDF 输出      更新时间:2023-09-26

我有一个生成PDF文件的URL。对于生成PDF,我使用iframe来加载该url并在同一页面为用户生成PDF文件。

当用户点击按钮时,屏幕上会显示loader。它应该隐藏当iframe加载完成(当PDF下载弹出)。我使用下面的代码,但它不工作,loader仍然显示后下载弹出打开(如果我改变url与任何其他像google.com然后它将工作)。

这是我的代码片段。

$("#test").click(function(){
  iframe = document.getElementById("download-container1");
  if (iframe === null)
  {
    $("#ajax_loading").show();
    var url="http://test.coachfxlive.com/ajax/ajax-action.php?type=s&vid=0&playlist_id=11&perpage=1&action=get_profile";
    iframe = document.createElement('iframe');  
    iframe.id = "download-container1";
    document.body.appendChild(iframe);
    $('#download-container1').load(function () {
      $("#ajax_loading").hide();
    });
    iframe.src=url;
  }
  
});
.ajax_loading {
    background-color: rgba(0, 0, 0, 0.7);
    display: none;
    height: 100%;
    left: 0;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 99999;
}
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="ajax_loading" id="ajax_loading"><span>Please Wait... Loading</span></div>
    <button id="test">click</button>
  </body>
</html>

iframe加载完成后,需要隐藏div ajax_loading。我做错什么了吗?还有其他解决办法吗?

您可以使用readystate iframe属性来检查iframe是否已完全加载。然而,如果内容是二进制文件,这在Chrome中不起作用。

一旦设置了iframe url,它每秒钟检查一次iframe readystate属性:

$("#test").click(function(){
 iframe = document.getElementById("download-container1");
 if (iframe === null)
 {
  $("#ajax_loading").show();
  var url="http://test.coachfxlive.com/ajax/ajax-action.php?type=s&vid=0&playlist_id=11&perpage=1&action=get_profile";
  iframe = document.createElement('iframe');  
  iframe.id = "download-container1";
  document.body.appendChild(iframe);
  //$('#download-container1').load(function () {
  //     $("#ajax_loading").hide();
  //});
  iframe.src=url;
  checkFinishedDownload(iframe);
}
 });
function checkFinishedDownload(ifr) {
     if (ifr.readyState == "complete" || ifr.readyState == "interactive") {
         // Here hide the spinner
         $("#ajax_loading").hide();
    }
     else {
        setTimeout(function () {
            checkFinishedDownload(ifr);
        }, 1000);
     }
}
 }
检查我的问题:Iframe。readyState在chrome中不工作 编辑:

在firefox中,你可以使用onload事件:

function checkFinishedDownload(ifr) {
     if ($.browser.mozilla) {
         ifr.onload = function () {
            $("#ajax_loading").hide();
          }
     }else{
          iframeCheck(ifr);
     }
}
function iframeCheck(iframe){
       if (iframe.readyState == "complete" || iframe.readyState == "interactive") {
         // Here hide the spinner
         $("#ajax_loading").hide();
    }
     else {
        setTimeout(function () {
            checkFinishedDownload(iframe);
        }, 1000);
     }
}