Download a file and redirect it to another page via ajax

后端 未结 12 2393
盖世英雄少女心
盖世英雄少女心 2021-02-02 09:44

I have a simple contact form for download excel file . Main issue happen , When ajax load .I want to download excel file then redirect user to a next page.. Below is my code wit

12条回答
  •  [愿得一人]
    2021-02-02 10:08

    1) Ajax is not a solution.

    2) window.open() popup will be blocked in most browsers even from same domain (at least that was happening in chrome and FF some time ago, when I tried to implement something similar)

    Something like this would do the job: (It doesn't check stuff like code returned, so 404 or non-file output will cause a redirect without downloading)

    document.getElementById('zzz').onclick = function() {
      ifrm = document.createElement('iframe');
      ifrm.style.display = "none";
    
      ifrm.src = "https://github.com/SheetJS/test_files/blob/b07031a7bd5a8b86b9baac94267f20cf81c6d5eb/A4X_2013.xls?raw=true"; 
    // some random xls file from github (it contains just a single "x" character in cell A-4)
      
      ifrm.onload = function() {
        window.location.href = "https://jquery.com";
      };
      
      document.body.appendChild(ifrm);
      return false;
    }
    
    click me
    

    P.S.: You will want application/octet-stream Content-type header for some file types (like pdf) to force browser to download file instead of using built-in viewers.

提交回复
热议问题