6

我的代码在 jquery 1.4 中运行良好,我尝试将其升级到 1.5。但是这部分代码停止工作 - 它的标准 beforeSend 处理程序

beforeSend: function (xhr, options) {
//
__forced_abort = false;

//
xhr.upload.addEventListener('progress', on_progress, false);
xhr.upload.addEventListener('load', on_loaded, false);
xhr.addEventListener('abort', on_abort, false);
....

我知道在 1.5 中还没有真正的 xhr - 只是 jqXHR 高级抽象,似乎 jqXHR 没有上传属性。

问题:如何在 jQuery 1.5 中获取纯(旧)xhr 对象?

4

3 回答 3

12

如果您的 beforeSend 是全球性的:

var oldXHR = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function() {
    var xhr = oldXHR();
    if(xhr instanceof window.XMLHttpRequest) {
        xhr.upload.addEventListener('progress', on_progress, false);
        xhr.upload.addEventListener('load', on_loaded, false);
        xhr.addEventListener('abort', on_abort, false);
    }
    return xhr;
};

如果您的 beforeSend 特定于特定请求:

$.ajax({
    xhr: function() {
        var xhr = jQuery.ajaxSettings.xhr();
        if(xhr instanceof window.XMLHttpRequest) {
            xhr.upload.addEventListener('progress', on_progress, false);
            xhr.upload.addEventListener('load', on_loaded, false);
            xhr.addEventListener('abort', on_abort, false);
        }
        return xhr;
    }
});
于 2011-04-07T08:27:32.067 回答
2

扩展拉斐尔的答案以包括百分比......

        $.ajax({ 
            type: 'POST',
            success: function(data) 
            {   

            }
            xhr: function() {
                var xhr = jQuery.ajaxSettings.xhr();
                if(xhr instanceof window.XMLHttpRequest) {
                    xhr.upload.addEventListener('progress', function(){
                        var percent = 0;
                        var position = event.loaded || event.position; /*event.position is deprecated*/
                        var total = event.total;
                        if (event.lengthComputable) {
                            percent = Math.ceil(position / total * 100);
                        }

                        var percentVal = percent+ '%';
                        $('#progressBar').css('width',percentVal);
                        $('#uploadPercentage').html(' '+percentVal);
                    }, false);
                }
                return xhr;
            },                                  
        }); 
于 2013-11-14T23:59:02.187 回答
0

尝试使用 jQuery.ajaxSettings.xhr()

于 2011-02-06T19:59:11.097 回答