问题描述
我有一个 Django 项目的问题。我开发了一个按钮,它应该生成和下载一个 csv 文件。实现这个功能的时间很长,所以我使用了celery任务来避免只有一个用户下载时独占服务器。
为此,我有一个 ajax 函数,它调用 api 并等待生成文件的结束。如果用户停留在同一页面上,则效果很好。
<a class="dropdown-item" onclick="exportToExcel('mission','man')">TEST</a>
function exportToExcel(expt,t){
var selectedTime = $("#weekSelect").children("option:selected").val();
var week = '';
var year = '';
if (selectedTime)
{
var week = selectedTime.toString().split("/")[0].substring(1);
var year = selectedTime.toString().split("/")[1];
}
var current_path = location.pathname;
var manager = current_path.split("/")[1];
var url = "";
if (week === ""){
url = `/api/export/${expt}-${manager}/${t}/`;
}
else
{
url = `/api/export/${expt}-${manager}/${t}/${week}-${year}/`;
}
console.log(url)
$.get(url).done(function ExportAsyncResults(data) {
// bind syncResults to itself to avoid clashing with the prior get request
context: this
// see the URL setup for where this url came from
const exportAsyncUrl = `/api/export_async_results/${data.task_id}/`
$.get(exportAsyncUrl)
.done(function(asyncData,status,xhr) {
context: this
// if the status doesn't respond with 202,that means that the task finished successfully
if (xhr.status !== 202) {
// stop making get requests to AsyncResults
clearTimeout(ExportAsyncResults);
// to download - create an anchor element and simulate a click
const a = document.createElement('a');
document.body.appendChild(a);
a.style='display: none';
a.href=asyncData.location;
a.download=asyncData.filename;
a.click();
a.remove()
$.get(`/api/del/${asyncData.filename}/`)
}
// async task still processing
else {
// Call the function pollAsyncResults again after
// waiting 1 second.
setTimeout(function() { ExportAsyncResults(data) },10000);
}
})
// see PollAsyncResultsView in View Setup. If the celery
// task fails,and returns a JSON blob with status_code
// 500,PollAsyncResultsView returns a 500 response,// which would indicate that the task Failed
.fail(function(xhr,error) {
// stop making get requests to AsyncResults
clearTimeout(ExportAsyncResults);
// add a message,modal,or something to show the user
// that there was an error the error in this case
// would be related to the asynchronous task's
// error message
})
})
.fail(function(xhr,error) {
// add a message,or something to show the user
// that there was an error
// The error in this case would be related to the main
// function that makes a request to start the async task
})
}
但是,如果用户离开页面转到另一个页面,我将丢失 api 响应并且下载永远不会发生。
所以我的问题是:如果用户在过程中更改页面,我该如何管理 ajax get 请求?
我读了这个 stackoverflow Change page in the middle of Ajax request,看来我必须阻止用户离开页面?
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)