Home >Web Front-end >JS Tutorial >How to Trigger File Downloads Asynchronously with Ajax?
Downloading Files Asynchronously Using Ajax
When downloading a file using Ajax, the returned data is typically displayed as a Binary stream. However, if you wish to open a file download window, you can take the following steps:
2019 Modern Browsers Update
This approach is recommended for modern browsers:
Code Example:
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(resp => resp.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = 'todo-1.json'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); alert('your file has downloaded!'); }) .catch(() => alert('oh no!'));
The above is the detailed content of How to Trigger File Downloads Asynchronously with Ajax?. For more information, please follow other related articles on the PHP Chinese website!