gpt4 book ai didi

python - 有没有办法可以在 ajax 调用的成功函数中下载文件?

转载 作者:行者123 更新时间:2023-12-01 04:35:04 25 4
gpt4 key购买 nike

我有一个网站,用户可以选择他们想要查看的数据。我想要的是在服务器端动态创建一个文件,然后在ajax调用的成功函数中为用户下载它。我目前拥有的是一个按钮

<div class='col-md-12 text-center'>
<button class='btn btn-link' id='download-data-file'>Download Data File</button>
</div>

单击时应触发 ajax 调用来创建文件。类似的东西

$.ajax({
url: '/createDataFile/',
method: 'POST',
data: data,
datatype: 'json',
success: function(data, status, xhr){
//Here Is where I am uncertain as to how to download the file for the user
},
error: function(xhr, status, err) {
//Some error code
});

为此目的,只需假设数据已经是 json。

有一些事情我不确定。 1.在我的服务器端代码(Python)中,我应该返回我创建的文件对象,还是应该将文件保存到本地磁盘,然后返回本地文件的文件名。 2. 在ajax success函数中,如何下载我刚刚为用户创建的文件?

为了清楚起见,我不需要任何创建文件的帮助,只需实际为用户下载它即可

谢谢!!

最佳答案

使用download属性创建 anchor 标记

删除dataType:'JSON'

使用 anchor 标记中的 ajax 调用中的 responce 进行下载。将 anchor 标记添加到正文并单击它。

success: function(data, status, xhr){
var a = document.createElement("a");
a.setAttribute("download","filename.json");
a.setAttribute("href","data:application/json,"+data);
document.body.appendChild(a);
a.click();
//document.body.removeChild(a);
}

var a = document.createElement("a");
a.setAttribute("download","fname.json");
a.setAttribute("href","data:application/json,{ 'num' : 5 }");
document.body.appendChild(a);
a.click();
console.log('Downloaded successfully!');

关于python - 有没有办法可以在 ajax 调用的成功函数中下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58958733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com