[英]Download file without refreshing the page using JSP/Servlet/Ajax
[英]Download file without refreshing the page
我有一个 javascript 页面,它有一个包含某些详细信息的表格。 单击一行,它将下载一个 JSON 文件。 我可以下载文件,但下载后页面会刷新。
function testDownload() {
const data = { a: "ajith", b: "kumar" };
const dataStr =
"data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
const downloadAnchorNode = document.createElement("a");
downloadAnchorNode.setAttribute("href", dataStr);
debugger;
downloadAnchorNode.setAttribute("id", "anchor");
downloadAnchorNode.setAttribute("download", "extracted" + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
}
下载完成后如何限制页面刷新?
如果您单击按钮下载 JSON,请尝试以下代码:
function testDownload(e) {
e.preventDefault();
const data = { a: "ajith", b: "kumar" };
const dataStr =
"data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
const downloadAnchorNode = document.createElement("a");
downloadAnchorNode.setAttribute("href", dataStr);
debugger;
downloadAnchorNode.setAttribute("id", "anchor");
downloadAnchorNode.setAttribute("onclick", "testDownloadFun(event)");
downloadAnchorNode.setAttribute("download", "extracted" + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
}
我添加了“preventDefault”方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.