原创之原生态ajax写法

整理一个纯种的ajax写法,如果有兴趣的朋友可以收藏,有利于对ajax的理解,当然jquery也挺好用的。


function zyajax() {}
zyajax.version = "1.1";
zyajax.async = true;
zyajax.httpMethod = "POST";
zyajax.responseType = "xml";
zyajax.url = "";
zyajax.debug = false;
zyajax.getXmlHttpObj = function() {
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var aVersion = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
        for (var i = 0; i < aVersion.length; i++) {
            try {
                var oXmlHttp = new ActiveXObject(aVersion[i]);
                return oXmlHttp;
            } catch(e) {}
        }
    }
    throw new Error("XMLHttp object can't be create!");
};
//
//  使用XMLHTTP和远程服务器通信。
//
//  参数名称        必须    类型        取值范围            描述
//-------------------------------------------------------------------------------------------
//async是      boolean     true/false          是否使用异步方式
//httpMethod是      string      "post"/"get"        http方法
//responseType否      string      "text"/"xml"        返回数据的类型
//url是      string                          接收请求的URL地址
//callback否      function                        异步方式操作完成时执行的回调函数
//postData否      string                          post方式时发送的数据
//
//  注:非必须的参数,如不被传递时使用null代替。
//zyajax.transmit = function(async, httpMethod, responseType, url, callback, postData)
//------------------------
//使用XMLHTTP和远程服务器通信。
//
//  参数名称        必须    类型        取值范围            描述
//-------------------------------------------------------------------------------------------
//qwzyCommond是      string      PHP端执行函数名          
//postData是      string      参数       JSON格式:{parameters:["param1","param2","param3"]}
//async否      boolean     true/false        是否使用异步方式
//callback是      string      回调函数                    
//------------------------
zyajax.call = function(qwzyCommond, postData, async, callback) {
    var httpMethod = zyajax.httpMethod;
    var responseType = zyajax.responseType;
    var url = zyajax.url;
    var params = "";
    objParams = postData["parameters"];
    if (objParams.length != 0) {
        for (var a = 0; a < objParams.length; a++) {
            params += objParams[a] + "~*zyzajax*~";
        }
        params = params.substring(0, params.length - 11)
    }
    params = "sbmtData=" + encodeURIComponent(params) + "&qwzyCommond=" + qwzyCommond;
    httpMethod = httpMethod.toLowerCase();
    if (responseType != null) responseType = responseType.toLowerCase();
    var xmlhttp = this.getXmlHttpObj();
    url = url + "?" + params;
    xmlhttp.open(httpMethod, url, async);
    if (!async && httpMethod == "post") xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    if (async) {
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                try {
                    if (typeof(callback) == "function") {
                        switch (responseType) {
                        case "xml":
                            var cmdXML = xmlhttp.responseXML;
                            var elements = cmdXML.getElementsByTagName("cmd");
                            var xmlLen = elements.length;
                            var returnValue = "";
                            for (var a = 0; a < xmlLen; a++) {
                                if (elements[a].getAttribute("cmd") == "txt") {
                                    returnValue = zyajax.getContent(elements[a]);
                                } else {
                                    eval(zyajax.getContent(elements[a]));
                                }
                            }
                            callback(returnValue);
                            break;
                        case "json":
                            var jsonData = eval("(" + xmlhttp.responseText + ")");
                            var jsonLen = jsonData.length;
                            var returnValue = "";
                            for (var a = 0; a < jsonLen; a++) {
                                if (jsonData[a].cmd == "txt") {
                                    returnValue = jsonData[a].code;
                                } else {
                                    eval(jsonData[a].code);
                                }
                            }
                            callback(returnValue);
                            break;
                        default:
                            callback(null);
                        }
                        if (zyajax.debug) {
                            alert("请求/响应函数:" + qwzyCommond);
                            alert("服务端返回内容:\n" + xmlhttp.responseText);
                        }
                    }
                } finally {
                    xmlhttp = null;
                }
            }
        }
        xmlhttp.send(params);
    } else {
        var returnValue = "";
        xmlhttp.send(params);
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            switch (responseType) {
            case "xml":
                var cmdXML = xmlhttp.responseXML;
                var elements = cmdXML.getElementsByTagName("cmd");
                var xmlLen = elements.length;
                for (var a = 0; a < xmlLen; a++) {
                    if (elements[a].getAttribute("cmd") == "txt") {
                        returnValue = zyajax.getContent(elements[a]);
                    } else {
                        eval(zyajax.getContent(elements[a]));
                    }
                }
                return returnValue;
                break;
            case "json":
                var jsonData = eval("(" + xmlhttp.responseText + ")");
                var jsonLen = jsonData.length;
                var returnValue = "";
                for (var a = 0; a < jsonLen; a++) {
                    if (jsonData[a].cmd == "txt") {
                        returnValue = jsonData[a].code;
                    } else {
                        eval(jsonData[a].code);
                    }
                }
                return returnValue;
                break;
            default:
                return null;
            }
            if (zyajax.debug) {
                alert("请求/响应函数:" + qwzyCommond);
                alert("服务端返回内容:\n" + xmlhttp.responseText);
            }
        } else {
            return null;
        }
    }
};
//简洁zyajax请求
zyajax.speedsmit = function(params, commond, callback) {
    var async = zyajax.async;
    var httpMethod = zyajax.httpMethod;
    var responseType = zyajax.responseType;
    var url = zyajax.url;
    var myMethod = zyajax.myMethod;
    var params = "sbmtData=" + encodeURIComponent(params) + "&qwzyCommond=" + commond;
    var httpMethod = httpMethod.toLowerCase();
    if (responseType != null) responseType = responseType.toLowerCase();
    var xmlhttp = this.getXmlHttpObj();
    url = url + "?" + params;
    xmlhttp.open(httpMethod, url, async);
    if (!async && httpMethod == "post") xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    if (async) {
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                try {
                    if (typeof(callback) == "function") {
                        switch (responseType) {
                        case "xml":
                            var cmdXML = xmlhttp.responseXML;
                            var elements = cmdXML.getElementsByTagName("cmd");
                            var xmlLen = elements.length;
                            var returnValue = "";
                            for (var a = 0; a < xmlLen; a++) {
                                if (elements[a].getAttribute("cmd") == "txt") {
                                    returnValue = zyajax.getContent(elements[a]);
                                } else {
                                    eval(zyajax.getContent(elements[a]));
                                }
                            }
                            callback(returnValue);
                            break;
                        case "json":
                            var jsonData = eval("(" + xmlhttp.responseText + ")");
                            var jsonLen = jsonData.length;
                            var returnValue = "";
                            for (var a = 0; a < jsonLen; a++) {
                                if (jsonData[a].cmd == "txt") {
                                    returnValue = jsonData[a].code;
                                } else {
                                    eval(jsonData[a].code);
                                }
                            }
                            callback(returnValue);
                            break;
                        default:
                            callback(null);
                        }
                        if (zyajax.debug) {
                            alert("请求/响应函数:" + commond);
                            alert("服务端返回内容:\n" + xmlhttp.responseText);
                        }
                    }
                } finally {
                    xmlhttp = null;
                }
            }
        }
        xmlhttp.send(params);
    } else {
        var returnValue = "";
        xmlhttp.send(params);
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            switch (responseType) {
            case "xml":
                var cmdXML = xmlhttp.responseXML;
                var elements = cmdXML.getElementsByTagName("cmd");
                var xmlLen = elements.length;
                for (var a = 0; a < xmlLen; a++) {
                    if (jsonData[a].cmd == "txt") {
                        returnValue = jsonData[a].code;
                    } else {
                        eval(jsonData[a].code);
                    }
                }
                break;
            case "json":
                var jsonData = eval("(" + xmlhttp.responseText + ")");
                var jsonLen = jsonData.length;
                for (var a = 0; a < jsonLen; a++) {
                    if (jsonData[a].cmd == "txt") {
                        returnValue = jsonData[a].code;
                    } else {
                        eval(jsonData[a].code);
                    }
                }
                return returnValue;
                break;
            default:
                return null;
            }
            if (zyajax.debug) {
                alert("请求/响应函数:" + commond);
                alert("服务端返回内容:\n" + xmlhttp.responseText);
            }
        } else {
            return null;
        }
    }
    return returnValue;
};
zyajax.request = function() {
    var arguNum = arguments.length;
    if (arguNum != 0) {
        var objParams = arguments[1]["parameters"];
        var params = "";
        if (objParams.length != 0) {
            for (var a = 0; a < objParams.length; a++) {
                params += objParams[a] + "~*zyzajax*~";
            }
            params = params.substring(0, params.length - 11);
        }
        return zyajax.speedsmit(params, arguments[0]["zyajaxfun"], zyajax.myMethod);
    }
}
zyajax.getContent = function(domObj) {
    if (!- [1, ]) {
        return domObj.text;
    } else {
        return domObj.textContent;
    }
}
//通过同步GET方式获得指定服务端的数据
//url 指定的服务端处理文件路径
zyajax.getText = function(url) {
    var xmlhttp = this.getXmlHttpObj();
    xmlhttp.open("GET", url, false);
    xmlhttp.send(null);
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        return xmlhttp.responseText;
    } else {
        return null;
    }
};
//通过同步POST方式获得指定服务端的数据
//url 指定的服务端处理文件路径
//post 发送的数据
zyajax.postText = function(url, postData) {
    var xmlhttp = this.getXmlHttpObj();
    xmlhttp.open("POST", url, false);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(postData);
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        return xmlhttp.responseText;
    } else {
        return null;
    }
};
//以异步GET方式获得指定服务端的数据
//url 指定的服务端处理文件
//callback 异步处理方法
zyajax.asyncGetText = function(url, callback) {
    var xmlhttp = this.getXmlHttpObj();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            try {
                if (typeof(callback) == "function") {
                    callback(xmlhttp.responseText);
                }
            } finally {
                xmlhttp = null;
            }
        }
    }
    xmlhttp.send(null);
};
//以异步Post方式获得指定服务端的数据
//url 指定的服务端处理文件
//callback 异步处理方法
//post 发送的数据
zyajax.asyncPostText = function(url, callback, postData) {
    var xmlhttp = this.getXmlHttpObj();
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            try {
                if (typeof(callback) == "function") {
                    callback(xmlhttp.responseText);
                }
            } finally {
                xmlhttp = null;
            }
        }
    }
    xmlhttp.send(postData);
};
//通过同步GET方式获得指定服务端的数据
//url 指定的服务端处理文件路径
zyajax.getXml = function(url) {
    var xmlhttp = this.getXmlHttpObj();
    xmlhttp.open("GET", url, false);
    xmlhttp.send(null);
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        return xmlhttp.responseXML;
    } else {
        return null;
    }
};
//通过同步Post方式获得指定服务端的数据
//url 指定的服务端处理文件路径
//post 发送的数据
zyajax.postXml = function(url, postData) {
    var xmlhttp = this.getXmlHttpObj();
    xmlhttp.open("POST", url, false);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(postData);
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        return xmlhttp.responseXML;
    } else {
        return null;
    }
};
//以异步GET方式获得指定服务端的数据
//url 指定的服务端处理文件
//callback 异步处理方法
zyajax.asyncGetXml = function(url, callback) {
    var xmlhttp = this.getXmlHttpObj();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            try {
                if (typeof(callback) == "function") {
                    callback(xmlhttp.responseXML);
                }
            } finally {
                xmlhttp = null;
            }
        }
    }
    xmlhttp.send(null);
};
//以异步Post方式获得指定服务端的数据
//url 指定的服务端处理文件
//callback 异步处理方法
zyajax.asyncPostXml = function(url, callback, postData) {
    var xmlhttp = this.getXmlHttpObj();
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            try {
                if (typeof(callback) == "function") {
                    callback(xmlhttp.responseXML);
                }
            } finally {
                xmlhttp = null;
            }
        }
    }
    xmlhttp.send(postData);
};

最后打个广告:喜欢h5的可以加群:517724501


上一篇》:前端开发面试笔试题汇总

下一篇》:JS事件冒泡

评论(1)

  • lovefree
    2016-06-23 10:53:43评论
    写的不错,考虑比较深!

请先登录后再评论,如果没有账号请先注册

发表评论