如何在没有jQuery的情况下处理Ajax浏览器兼容性?

时间:2014-12-21 21:20:47

标签: javascript ajax

我有js函数如下

//getting element by id
function _(x){
    return document.getElementById(x);
}

//ajax request handling

function ajaxObj( meth, url ) {
    var x = new XMLHttpRequest();
    x.open( meth, url, true );
    x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    return x;
}
function ajaxReturn(x){
    if(x.readyState == 4 && x.status == 200){
       return true; 
    }
}

如何在没有jQuery的情况下处理浏览器兼容性?

1 个答案:

答案 0 :(得分:0)

如果你谷歌有很多不同的选择,但这里有一个我找到的: https://github.com/ilinsky/xmlhttprequest

基本思想是我认为你会发现有用的,以及他们如何决定使用哪个课程。

var oXMLHttpRequest = window.XMLHttpRequest;

// Define on browser type
var bGecko  = !!window.controllers;
var bIE     = !!window.document.namespaces;
var bIE7    = bIE && window.navigator.userAgent.match(/MSIE 7.0/);

// Enables "XMLHttpRequest()" call next to "new XMLHttpRequest()"
function fXMLHttpRequest() {
    if (!window.XMLHttpRequest || bIE7) {
        this._object = new window.ActiveXObject("Microsoft.XMLHTTP");
    } // only use initial XHR object internally if current reference to XHR is our normalized replacement 
    else if (window.XMLHttpRequest.isNormalizedObject) {
        this._object = new oXMLHttpRequest();
    } // otherwise use whatever is currently referenced by XMLHttpRequest
    else {
        this._object = new window.XMLHttpRequest();     
    }