download file using an ajax request

后端 未结 12 2353
旧时难觅i
旧时难觅i 2020-11-21 23:46

I want to send an \"ajax download request\" when I click on a button, so I tried in this way:

javascript:

var xhr = new XMLHttpRequest();
xhr.open(\         


        
12条回答
  •  -上瘾入骨i
    2020-11-22 00:32

    It is possible. You can have the download started from inside an ajax function, for example, just after the .csv file is created.

    I have an ajax function that exports a database of contacts to a .csv file, and just after it finishes, it automatically starts the .csv file download. So, after I get the responseText and everything is Ok, I redirect browser like this:

    window.location="download.php?filename=export.csv";
    

    My download.php file looks like this:

    
    

    There is no page refresh whatsoever and the file automatically starts downloading.

    NOTE - Tested in the following browsers:

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

提交回复
热议问题