简体   繁体   English

单击按钮时下载文件jQuery

[英]Download File When Button is Clicked jQuery

I have the following button in my HTML: 我的HTML中有以下按钮:

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

I have the following jQuery code that executes when the button is clicked: 我有以下单击按钮时执行的jQuery代码:

$(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. 单击此按钮后,createVCard.php脚本将创建一个vCard并将文件作为下载内容发送到浏览器。 In Safari, it works just fine. 在Safari中,它可以正常工作。 However, in Google Chrome, I am getting the following error in the console: 但是,在Google Chrome浏览器中,控制台出现以下错误:

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? 是否有人像在Safari中一样建议在Chrome中下载文件?

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: 我了解chrome这个问题的唯一方法是在<a>标记内指定HTML5下载属性 ,要使用此属性 ,您的代码将更改为:

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

Or, with JQuery, perhaps something like: (Untested) 或者,使用JQuery,可能类似于:(未经测试)

$(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 您需要确保在链接中设置了href属性,jQuery才能正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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