Failed to override the getResponseHeader method on XMLHttpRequest

廉价感情. 提交于 2019-12-12 10:11:55

问题


I was trying to override the getResponseBody method on XMLHttpRequest object. The code looks so:

xhr.onreadyStateChange = function(){
    if (xhr.readyState !== 4) {
        return;
    }
    if (xhr.status === 200) {
        // callback to handle the result
    } else {
        var _orig = xhr.getResponseHeader;
        xhr.getResponseHeader = function(name){
            return decodeHeader(_orig.apply(xhr,[name]));
        };
        // callback to handle the failure
    }
}

It throws an error "Object doesn't support this property or method" when calling the _orig.apply.

Any idea? Thanks.

PS: I create a new XHR object every time and do not reuse the old one.


回答1:


XMLHttpRequest is a host object (i.e. an object provided by the environment to represent something about the environment rather than part of the language), and host objects can essentially do whatever they like. They're not bound by the same rules as built-in objects. IE is particularly notable for making use of this freedom and many of its host objects (including XMLHttpRequest) do not behave as one might hope.

For this reason, it's better not to try and add or change any property of any host object. Instead, write your own XMLHttpRequest wrapper.



来源:https://stackoverflow.com/questions/3581959/failed-to-override-the-getresponseheader-method-on-xmlhttprequest

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