点击jQuery按钮下载文件
Download File When Button is Clicked jQuery
我的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,下载文件。
相关文章:
- asp.net网站文件下载历史记录
- Firefox,如何提交表单触发文件下载,但停留在网页上
- Interent Explorer中的数据URI文件下载
- 将页面上的文本替换为 jQuery 并提示文件下载
- JavaScript文件下载
- 是否可以触发文件下载到用户的浏览器
- Javascript JSON 到 Excel 文件下载
- 使用Javascript将多个文件下载为zip文件或文件夹
- 巴比伦JS-场景从本地文件下载
- 文件下载html与错误处理FileNotFound
- 使用jQuery捕获站点范围内的文件下载
- 在WinJS中将文件下载到文件系统
- JQuery启动文件下载,然后运行一个函数
- 文件下载无法在firefox上运行
- 创建文件下载js
- 如何使用JQuery禁用pdf文件下载选项
- 使用JavaScript/Jquery创建文本文件下载/更新到本地客户端机器中的特定位置
- CollectionFS中是否存在用于文件下载的事件侦听器/回调
- 文件下载后,Document Ready无法工作
- 浏览器不生成文件下载对话框