是否应将异步设置为 true 或在卸载前使用 jQuery 以防止用户在文件上传期间离开



如果您混合使用 jQuery 和 Ajax 来管理用户上传表单的前端,如下所示:

$('form :button').click(function(){
    var formData = new FormData($("form")[0]);
    $.ajax({
        url: '/upload',
        type: 'POST',
        xhr: function() {
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){
                myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
            }
            return myXhr;
        },
        data: formData,
        success: function (res) {
            alert("Uploaded");
        },
        cache: false,
        contentType: false,
        processData: false
    });
});

使用async:false停止所有浏览器移动直到上传完成或使用某种jQuery函数(例如beforeunload)来通知用户离开页面会中断他们的上传是否有意义?

$(window).bind('beforeunload', function(){
    return 'If you leave this page, your upload will not complete! Continue?';
});

Ajax 中是否有仅在上传过程中运行函数的选项,以便此警告仅在文件上传期间出现?

最好

在上传过程开始时保存一个标志:

$('form :button').click(function(){
    var formData = new FormData($("form")[0]);
    var $this = $(this);
    $this.data('uploading', true);
    $.ajax({
       ..., // your attributes
       success: function (res) {
           $this.data('uploading', false);
           alert("Uploaded");
       },
    ... // rest of your code
});

然后在beforeunload

$(window).bind('beforeunload', function(){
    if($('form :button').data('uploading') === true) {
       return 'If you leave this page, your upload will not complete! Continue?';
    }
});

最新更新