Home >Web Front-end >JS Tutorial >How Can I Download a File Using JavaScript or jQuery Without Reloading the Page?
When the user clicks on a hyperlink, it typically opens the corresponding content within the current web page. However, there are scenarios where you need to manually trigger a file download without replacing the page's content.
To achieve this, you can utilize two main approaches:
1. Using an Invisible iFrame:
Create an invisible iframe element in your HTML:
<iframe>
Then, use JavaScript to set the iframe's "src" attribute to the file URL:
function Download(url) { document.getElementById('my_iframe').src = url; }
To prevent the browser from interpreting certain files (e.g., HTML, text) as web pages and force them to be downloaded, you may need to set their MIME type to "application/x-please-download-me" or "application/octet-stream" on the server side.
2. Opening the File in a New Tab:
To open the download in a new tab, you can modify the hyperlink's target attribute:
<a href="file.pdf" target="_blank">Download</a>
Alternatively, use jQuery to dynamically set the target attribute:
$('a#someID').attr({target: '_blank', href: 'file.pdf'});
When the user clicks on the hyperlink, the target attribute ensures that the file is downloaded in a new tab or window.
The above is the detailed content of How Can I Download a File Using JavaScript or jQuery Without Reloading the Page?. For more information, please follow other related articles on the PHP Chinese website!