0

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

4

1 回答 1

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?';
    }
});
于 2012-05-11T02:12:54.307 回答