【问题标题】:How to stop a while loop with a click function?如何使用点击功能停止while循环?
【发布时间】:2014-03-25 11:22:33
【问题描述】:

这有点复杂:我有一个带有文件输入字段和下方上传按钮的表单。通过单击该上传按钮,将触发一个函数,该函数执行 ajax 调用以检查上传目录中是否已存在同名文件。如果文件不存在,则触发“start_upload”函数:

function start_upload(){
    while(start < SIZE) { //start and end is 0 and ~200Bytes - that's the size of the parts of the file
        i++;
        upload(blob.slice(start, end), i, name, SIZE);
        start = end;
        end = start + BYTES_PER_CHUNK;
    }
}

上传功能如下:

function upload(blobOrFile, part, name, size) {
    var formdata = new FormData();
    var xhr = new XMLHttpRequest();
    formdata.append('blob', blobOrFile);
    formdata.append('part', part);
    formdata.append('filename', name);
    xhr.open('POST', 'upload2.php', true);
    xhr.onload = function (e) {
        uploaders.pop();
        if (!uploaders.length) {
            //some code that's fired when upload has finished
        }
    };
    //some other irrelevant functions
    uploaders.push(xhr);
    xhr.send(formdata);

}

一切正常,但出于可用性原因,我也想创建一个取消上传按钮。我尝试了以下操作:

此取消功能会停止所有当前的“POST”请求,但会重新从零开始。

$("#cancel").click(function(){
    xhr.abort();
});

$( document ).ajaxStop(function() {
    //do something after all ajax requests are finished or aborted
});

知道如何永久中止上传吗?

【问题讨论】:

    标签: jquery ajax upload


    【解决方案1】:

    您可以为此使用标志值,如下所示:

     int flag=0;
        function start_upload(){
        while(start < SIZE && flag==0) { //start and end is 0 and ~200Bytes - that's the size of the parts of the file
            i++;
            upload(blob.slice(start, end), i, name, SIZE);
            start = end;
            end = start + BYTES_PER_CHUNK;
        }
    }
    

    您的取消按钮将是:

    $("#cancel").click(function(){
    flag=1;
    

    });

    希望它对你有用。

    【讨论】:

    • 是的,谢谢! :) 好吧,我不得不使用两个#cancel click 函数,它最终按预期工作,但现在一切都很好。两个函数,因为一个在函数外部改变了上传函数外部的全局标志变量(使用上传函数内部的函数将始终返回0),另一个在上传函数内部的#cancel函数使用xhr.abort();因为在函数外部 xhr 是未定义的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2013-09-11
    • 2023-01-10
    • 2015-03-18
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    相关资源
    最近更新 更多