views:

72

answers:

1

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.

+2  A: 

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.

Tim Down
Also see http://ajaxian.com/archives/ie7-xmlhttprequest-native-or-not
Marcel Korpel
Marcel: Yes. "Native" is an odd choice of word for any browser's implementation of `XMLHttpRequest`: it's always going to be a host object. For the web developer, that change in IE 7 has little practical impact until IE 6 is dead enough to ignore.
Tim Down