简体   繁体   中英

Download File When Button is Clicked jQuery

I have the following button in my HTML:

<button id="exportVCardButton">Export vCard</button>

I have the following jQuery code that executes when the button is clicked:

$(document).on('click', '#exportVCardButton', function (e) {
    e.preventDefault();
    document.location.href = 'contacts/createVCard.php?contactID=<?php echo $contactID; ?>';
});

When this button is clicked, the createVCard.php script creates a vCard and sends the file as a download to the browser. In Safari, it works just fine. However, in Google Chrome, I am getting the following error in the console:

Resource interpreted as Document but transferred with MIME type text/x-vcard

I have tried several different solutions but none seem to work. Does anybody have any suggestions to make the file download in Chrome as it does in Safari?

The only way I know around this issue with chrome is to specify the HTML5 download attribute inside an <a> tag, to use this your code would change to:

<a id="exportVCardButton" href="contacts/createVCard.php?contactID=<?php echo $contactID; ?>" download>Export vCard</a>

Or, with JQuery, perhaps something like: (Untested)

$(document).on('click', '#exportVCardButton', function (e) {
    e.preventDefault();
    var href = $('#exportVCardButton').attr('href');
    document.location.href = href;
});

You would need to make sure you have the href attribute set in your link for the jQuery to work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM