Best method of Instantiating an XMLHttpRequest object

前端 未结 9 1464
一生所求
一生所求 2020-12-31 20:43

What is the best method for creating an XMLHttpRequest object?

It should work in all capable browsers.

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 20:45

    I'd suggest following Sergey's advise or writing a small, less sophisticated patch for IE yourself:

    if(typeof window.XMLHttpRequest === 'undefined' &&
        typeof window.ActiveXObject === 'function') {
        window.XMLHttpRequest = function() {
            try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
            try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
            return new ActiveXObject('Microsoft.XMLHTTP');
        };
    }
    

    Then you can do

    var req = new XMLHttpRequest;
    

    even in IE.

    edit 2011-02-18: see this blogpost for the rationale behind the new choice of MSXML versions...

提交回复
热议问题