JavaScript - ajax请求的初步封装

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

将此成果小小的记录一下

tools.ajax = function (params) {
    if (!params.url) {
        throw "url is empty";
    }
    //默认设置
    var setting = {
        type: "get",
        async: true,
        data: {},
        dataType: "json",
        contentType: "application/x-www-form-urlencoded"
    };
    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            setting[key] = params[key];
        }
    }
    setting.data = getData(setting.contentType, setting.data);
    //根据数据类型调用不同方法
    setting.dataType == "jsonp" ? ajaxJsonp(setting) : ajaxJson(setting);

    function ajaxJsonp(options) {
        var callback = "BigMap_" + Math.random().toString().replace(/\D/g, "") + "_" + (new Date().getTime());

        var script = document.createElement("script");
        script.src = options.url + "?callback=" + callback + "&" + options.data;
        var head = document.getElementsByTagName("head")[0];
        head.appendChild(script);

        window[callback] = function (data) {
            options.success && options.success(data);
            script.parentNode.removeChild(script);
            clearTimeout(script.timer);
            delete window[callback];
        };

        script.timer = setTimeout(function () {
            clearTimeout(script.timer);
            delete window[callback];
            options.error && options.error("网络超时");
        }, 5000);
    }

    function ajaxJson(options) {
        var xmlHttp;
        try {
            //IE高版本创建xmlhttp
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (E) {
            try {
                //IE低版本创建xmlhttp
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                //兼容非IE浏览器,直接创建xmlhttp对象
                xmlHttp = new XMLHttpRequest();
            }
        }

        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");
                            return;
                        }

                    } else {
                        response = xmlHttp.responseText
                    }
                    options.success && options.success(response);
                } else {
                    options.error && options.error("Server error");
                }
            }
        };

        if (options.type.toUpperCase() === "GET") {
            xmlHttp.open("GET", options.url + "?" + options.data, options.async);
            xmlHttp.send(null);
        } else if (options.type.toUpperCase() === "POST") {
            xmlHttp.open("POST", options.url, options.async);
            xmlHttp.setRequestHeader("Content-Type", options.contentType);
            xmlHttp.send(options.data);
        }
    }

    function getData(contentType, data) {
        //如果contentType为application/json,那么传递过来的数据仅仅为json字符串
        if (contentType.search("application/json") !== -1) {
            return data;
        }

        if (data) {
            var arr = [];
            for (var name in data) {
                if (data.hasOwnProperty(name)) {
                    arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
                }
            }
            arr.push(("t=" + Math.random()).replace(".", ""));
            return arr.join("&");
        } else {
            return null;
        }
    }

};

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值