How to get pure XMLHTTPRequest object in jQuery 1.5?

谁说胖子不能爱 提交于 2019-11-29 14:41:16

问题


My code works fine in jquery 1.4 and i try upgrade it to 1.5. But this part of code stop working - its standard beforeSend handler

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);
....

I know that in 1.5 havent really xhr - just jqXHR highlevel abstraction and seems to be jqXHR not have upload attributes.

Question: how get pure (old) xhr object in jQuery 1.5?


回答1:


If your beforeSend was global:

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;
};

If your beforeSend was specific to a particular request:

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



回答2:


Extending Raphaels answer to include percentages...

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



回答3:


Try use jQuery.ajaxSettings.xhr()



来源:https://stackoverflow.com/questions/4915671/how-to-get-pure-xmlhttprequest-object-in-jquery-1-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!