你应该设置async true还是使用jQuery beforeunload来阻止用户在文件上传过程中离开?

时间:2012-05-11 02:04:52

标签: jquery html ajax

如果您使用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中是否有一个选项只在上传过程中运行一个函数,以便只在文件上传期间出现此警告?

1 个答案:

答案 0 :(得分:2)

在上传过程开始时保存标志可能更好:

$('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?';
    }
});