0

我最近刚开始学习 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 的部分原因是有很多方法可以完成相同的任务,我喜欢探索所有可能的选择。

4

2 回答 2

1
function four() {
  try {
    return new XMLHttpRequest(); 
  } catch (e) // Catch ReferenceError
    return new window.ActiveXObject("Microsoft.XMLHTTP");
  }
}
于 2012-05-01T14:39:57.993 回答
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;

资源

于 2012-05-01T14:37:34.087 回答