首页 > 开发 > AJAX > 正文

js与jQuery实现的兼容多浏览器Ajax请求实例

2024-09-01 08:28:35
字体:
来源:转载
供稿:网友

ajax我们经常会用到的,但网上找到的大部份ajax兼容性都不强,下面自己改了一个不错的兼容性很强的ajax函数,同时后面介绍的jquery ajax 兼容性也很强。

一、纯js实现的Ajax实例:
代码如下:var ajax = function() {};
ajax.prototype = {
    request: function(method, url, callback, postVars) {
        var xhr = this.createXhrObject();
        xhr.onreadystatechange = function() {
            if (xhr.readyState !== 4) return;
            (xhr.status === 200) ?
                callback.success(xhr.responseText, xhr.responseXML) :
                callback.failure(xhr,status);
        };
        if (method !== "POST") {
            url += "?" + JSONStringify(postVars);
            postVars = null;
        }
        xhr.open(method, url, true);
        xhr.send(postVars);
    },
    createXhrObject: function() {
        var methods = [
            function() { return new XMLHttpRequest(); },
            function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
            function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
        ],
        i = 0,
        len = methods.length;
        for (; i < len; i++) {
            try {
                methods[i];
            } catch(e) {
                continue;
            }
            this.createXhrObject = methods[i];
            return methods[i];
        }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表