Home > Web Front-end > JS Tutorial > How to Trigger File Downloads Asynchronously with Ajax?

How to Trigger File Downloads Asynchronously with Ajax?

Susan Sarandon
Release: 2024-12-25 02:19:14
Original
214 people have browsed it

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!'));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template