JavaScript - ajax请求的初步封装

来源:互联网 发布:制作视频剪辑的软件 编辑:程序博客网 时间:2024/05/16 01:00

在封装js开发包的时候,需要发送ajax请求,又不能强制用户使用jQuery,因此按照jQuery的风格,封装了一个ajax,

将此成果小小的记录一下

BigMap.ajax = function(options) {    if (!options.url) {        throw "url is empty";    }    var xmlHttp;    try {        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");//IE高版本创建XMLHTTP    } catch(E) {        try {            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE低版本创建XMLHTTP        } catch(E) {            xmlHttp = new XMLHttpRequest();//兼容非IE浏览器,直接创建XMLHTTP对象        }    }    options.type = (options.type || "GET").toUpperCase();    options.dataType = options.dataType || "json";    options.async = options.async == undefined ? true : options.async;    options.data = (function(data){        if (data) {            var arr = [];            for (var name in data) {                arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));            }            arr.push(("t=" + Math.random()).replace(".",""));            return arr.join("&");        } else {            return null;        }        })(options.data);    xmlHttp.onreadystatechange = function () {        if (xmlHttp.readyState == 4) {            if (xmlHttp.status == 200) {                var response;                if (options.dataType == "json") {                    try{                        response = eval("(" + xmlHttp.responseText + ")");                    } catch(e) {                        options.error && options.error("JSON parsing failed");                    }                                    } else {                    response = xmlHttp.responseText                }                options.success && options.success(response);            } else {                options.error && options.error("Server error");            }        }    }    if (options.type == "GET") {        xmlHttp.open("GET", options.url + "?" + options.data, options.async);        xmlHttp.send(null);    } else if (options.type == "POST") {        xmlHttp.open("POST", options.url, options.async);        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");        xmlHttp.send(options.data);    }}

其中可能存在不完善和不合理之处,如有发现,请不吝赐教



0 0
原创粉丝点击