微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

更改页面后 Ajax 请求丢失

如何解决更改页面后 Ajax 请求丢失

我有一个 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 举报,一经查实,本站将立刻删除。