如何在jQuery 1.5中获取纯XMLHTTPRequest对象?

时间:2011-02-06 19:48:55

标签: jquery xmlhttprequest jquery-1.5

我的代码在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对象?

3 个答案:

答案 0 :(得分: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;
    }
});

答案 1 :(得分:2)

扩展Raphaels答案包括百分比...

        $.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;
            },                                  
        }); 

答案 2 :(得分:0)

尝试使用jQuery.ajaxSettings.xhr()