Download File with AJAX Request
When attempting to initiate an "ajax download request" upon button click, it's common to implement code like the below:
var xhr = new XMLHttpRequest(); xhr.open("GET", "download.php"); xhr.send();
Along with the following PHP script:
<? header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename= file.txt"); header("Content-Transfer-Encoding: binary"); readfile("file.txt"); ?>
However, this approach may not yield the desired result. To effectively initiate a download, consider implementing one of the following alternatives:
Option 1: Utilize the 'download' Attribute
In modern browsers like Firefox and Chrome, the 'download' attribute offers a convenient way to initiate downloads from within a webpage without requiring server-side interaction. Here's an example:
<a href="file.txt" download="file.txt">Download</a>
Option 2: Navigate to the Download Script using AJAX or Window.location
If the 'download' attribute isn't a suitable option, you can use AJAX or window.location to navigate to the download script. Using AJAX, you can perform an asynchronous request and then use its success callback function to redirect to the download script:
$.ajax({ url: 'download.php', type: 'POST', success: function() { window.location = 'download.php'; } });
Alternatively, you can simply use window.location to navigate to the download script:
window.location = 'download.php';
While the AJAX approach provides some flexibility, using window.location is typically more efficient and straightforward.
The above is the detailed content of How to Trigger a File Download Using AJAX: Direct Download or Server-Side Redirect?. For more information, please follow other related articles on the PHP Chinese website!