我的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中,它运行得很好。然而,在谷歌Chrome中,我在控制台中收到以下错误:
Resource interpreted as Document but transferred with MIME type text/x-vcard
我尝试了几种不同的解决方案,但似乎都不起作用。有人建议像在Safari中那样在Chrome中下载文件吗?
我所知道的解决chrome问题的唯一方法是在<a>
标记中指定HTML5下载属性,要使用此属性,您的代码将更改为:
<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工作
它实际上非常简单。
<button onclick = document.getElementById("download").click()>Download</button> <a id = "download" href="file.txt" download="file.txt"></a>
这样做的目的是使下载href不可见,因此它不会显示在页面上。当人们点击该按钮时,该按钮会点击不可见的href,下载文件。