单击按钮时下载文件jQuery

时间:2015-03-23 21:27:56

标签: javascript php jquery html

我的HTML中有以下按钮:

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

我有以下单击按钮时执行的jQuery代码:

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

单击此按钮时,createVCard.php脚本会创建一个vCard,并将该文件作为下载文件发送到浏览器。在Safari中,它工作得很好。但是,在Google Chrome中,我在控制台中收到以下错误:

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

我尝试了几种不同的解决方案,但似乎都没有。有没有人建议在Chrome中像在Safari中一样下载文件?

1 个答案:

答案 0 :(得分:0)

我知道围绕此问题使用chrome的唯一方法是在<a>标记内指定HTML5 download attribute,使用此代码将更改为:

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

或者,使用JQuery,可能类似于:(未经测试)

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

您需要确保在链接中设置 href 属性才能使jQuery正常工作