File download script doesn't work when called from Ajax

后端 未结 5 674
青春惊慌失措
青春惊慌失措 2020-12-02 00:54

I\'m using the following script to initiate file downloads:

if (file_exists($newfilename)) {
    header(\'Content-Description: File Transfer\');
    header(\         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 01:43

    It is possible to download a file using AJAX.

    javascript:

    function exportToCsv(){
    
        var xmlhttp;
    
        if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest; }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    window.location="download.php?filename=export.csv";
                }
    
            }
        }
        request = "exportToCsv.php";
        xmlhttp.open("GET", request, true);
        xmlhttp.send();
    
    }
    

    The code above, exports a mysql database of contacts to a .csv file. After that, if everything is Ok (xmlhttp.readyState == 4) automatically starts the download. window.location="download.php?filename=export.csv";

    download.php file:

    
    

    After this, the browser just presents the "Save file as" dialog, and no page refresh happens whatsoever. I have the application up and running, and never had problems. Runs on the following browsers:

    Chrome v37.0.2062.120 
    Firefox v32.0.1
    Opera v12.17
    Internet Explorer v11
    

提交回复
热议问题