创建XMLHttpRequests的方法

时间:2012-05-01 14:29:07

标签: javascript ajax

我刚刚开始学习ajax,我正在研究创建HttpRequests的方法 这是我到目前为止提出的方法:

function one() {
if(window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
    alert('Other');
} else if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
    alert('windows');
}
return xhr;
}


function two() {
    if(window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
        alert('Other');
    } else if (!window.XMLHttpRequest) {
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
        alert('windows');
    }
    return xhr;
}

function three() {
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
        alert('Other');
    } else {
        xhr = new ActiveXObject();
        alert('windows');
    }
    return xhr;
}

function four() {
    try {
        xhr = new XMLHttpRequest();
        alert('Other');
    } catch (e) {
        xhr = new ActiveXObject();
        alert('windows');
    }
    return xhr;
}

我想了解更多创建请求的方法。如果有人有任何其他方法,请分享。我喜欢Javascript的一部分是有很多方法可以完成相同的任务,我喜欢探索所有可能的选项。

2 个答案:

答案 0 :(得分:1)

在寻找好的方法时,我通常会遵循jQuery,

// Functions to create xhrs
function createStandardXHR() {
    try {
        return new window.XMLHttpRequest();
    } catch( e ) {}
}

function createActiveXHR() {
    try {
        return new window.ActiveXObject( "Microsoft.XMLHTTP" );
    } catch( e ) {}
}

// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
    /* Microsoft failed to properly
     * implement the XMLHttpRequest in IE7 (can't request local files),
     * so we use the ActiveXObject when it is available
     * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
     * we need a fallback.
     */
    function() {
        return !this.isLocal && createStandardXHR() || createActiveXHR();
    } :
    // For all other browsers, use the standard XMLHttpRequest object
    createStandardXHR;

Source

答案 1 :(得分:1)

function four() {
  try {
    return new XMLHttpRequest(); 
  } catch (e) // Catch ReferenceError
    return new window.ActiveXObject("Microsoft.XMLHTTP");
  }
}