js封装 Ajax ——常用工具函数

在前端开辟中,ajax的重要性显而易见,所以我最先试着封装本身专属ajax
1.通例封装

/* 封装ajax函数
 * @param {string}opt.method http衔接的体式格局,包含POST和GET两种体式格局
 * @param {string}opt.url 发送要求的url
 * @param {boolean}opt.async 是不是为异步要求,true为异步的,false为同步的
 * @param {object}opt.data 发送的参数,花样为对象范例
 * @param {function}opt.success ajax发送并吸收胜利挪用的回调函数
 */
/*1通例封装*/
function ajax(opt) {
    opt = opt || {};
    opt.method = opt.method.toUpperCase() || "GET"; //GET:用"GET"体式格局发送数据,只能256KB;POST:用"POST"体式格局发送数据,能够大到4MB
    opt.url = opt.url || "";
    opt.async = opt.async || true; //同步异步
    opt.dataType = opt.dataType || "text"; //所传的数的数据范例
    opt.contentType = opt.contentType || "application/x-www-form-urlencoded; charset=utf-8"; //默许表单花样 opt.dataType='json'
    opt.data = opt.data || null;


    var xmlHttp = getXmlHttp(); //猎取XML 对象

    var postData = getAjaxParama(opt.data); //data

    if (opt.contentType === "application/json;charset=utf-8" && opt.dataType === "json") {
        postData = JSON.stringify(opt.data); //转化为字符串
    }

    if (opt.method === 'POST') {
        xmlHttp.open(opt.method, opt.url, opt.async);
        xmlHttp.setRequestHeader('Content-Type', opt.contentType); //而POST要求须要设置要求头,用来通报参数

    } else if (opt.method === 'GET') {
        postData = opt.url.indexOf("?") >= 0 ? "&" + postData : "?" + postData; //GET要求,参数是拼接到url上面;
        xmlHttp.open(opt.method, opt.url + postData, opt.async);
        postData = null; //重置参数
    }
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            var status = xmlHttp.status;
            if (status >= 200 && status < 300) {
                opt.success && opt.success(xmlHttp.responseText);
            } else {
                opt.error && opt.error(status);
            }
        }
    };

    xmlHttp.send(postData);

    function getXmlHttp() {
        var obj = null;
        //非IE浏览器建立XmlHttpRequest对象
        if (window.XMLHttpRequest) obj = new XMLHttpRequest();

        //IE浏览器建立XmlHttpRequest对象
        if (window.ActiveXObject) {
            try {
                obj = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e) {
                try {
                    obj = new ActiveXObject("msxml2.XMLHTTP");
                } catch (ex) {}
            }
        }
        return obj;

    }

    function getAjaxParama(data) {
        var params = [];

        for (var key in data) {
            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        }
        return params.join('&'); //增加&字符串

    }

}

2.自定义封装

/**
 * [ajax封装ajax函数]
 * @Author   Linada
 * @DateTime 2017-12-19T16:16:32+0800
 * @param {string}  opt.method [http衔接的体式格局,包含POST和GET两种体式格局]
 * @param {string}  opt.url [发送要求的url]
 * @param {boolean} opt.async [是不是为异步要求,true为异步的,false为同步的]
 * @param {object}  opt.data [发送的参数,花样为对象范例]
 * @param {function}  opt.success [ajax发送并吸收胜利挪用的回调函数]
 */

;(function (undefined) {
    "use strict"
    var _global;
    var umeAjax = {
        ajax: function (opt) {
            opt = opt || {};
            opt.method = opt.method.toUpperCase() || "GET"; //GET:用"GET"体式格局发送数据,只能256KB;POST:用"POST"体式格局发送数据,能够大到4MB
            opt.url = opt.url || "";
            opt.async = opt.async || true; //同步异步
            opt.dataType = opt.dataType || "text"; //所传的数的数据范例
            opt.contentType = opt.contentType || "application/x-www-form-urlencoded; charset=utf-8"; //默许表单花样 opt.dataType='json'
            opt.data = opt.data || null;


            var xmlHttp = getXmlHttp(); //猎取XML 对象

            var postData = getAjaxParama(opt.data); //data

            if (opt.contentType === "application/json;charset=utf-8" && opt.dataType === "json") {
                postData = JSON.stringify(opt.data); //转化为字符串
            }

            if (opt.method === 'POST') {
                xmlHttp.open(opt.method, opt.url, opt.async);
                xmlHttp.setRequestHeader('Content-Type', opt.contentType); //而POST要求须要设置要求头,用来通报参数

            } else if (opt.method === 'GET') {
                postData = opt.url.indexOf("?") >= 0 ? "&" + postData : "?" + postData; //GET要求,参数是拼接到url上面;
                xmlHttp.open(opt.method, opt.url + postData, opt.async);
                postData = null; //重置参数
            }
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4) {
                    var status = xmlHttp.status;
                    if (status >= 200 && status < 300) {
                        opt.success && opt.success(xmlHttp.responseText);
                    } else {
                        opt.error && opt.error(status);
                    }
                }
            };

            xmlHttp.send(postData);
        },


    }

    function getXmlHttp() {
        var obj = null;
        //非IE浏览器建立XmlHttpRequest对象
        if (window.XMLHttpRequest) obj = new XMLHttpRequest();

        //IE浏览器建立XmlHttpRequest对象
        if (window.ActiveXObject) {
            try {
                obj = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e) {
                try {
                    obj = new ActiveXObject("msxml2.XMLHTTP");
                } catch (ex) {
                }
            }
        }
        return obj;

    }


    function getAjaxParama(data) {
        var params = [];

        for (var key in data) {
            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        }
        return params.join('&'); //增加&字符串

    }

    // 末了将插件对象暴露给全局对象
    _global = (function () {
        return this || (0, eval)('this');
    }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = umeAjax;
    } else if (typeof define === "function" && define.amd) {
        define(function () {
            return umeAjax;
        });
    } else {
        !('umeAjax' in _global) && (_global.umeAjax = umeAjax);
    }
}());

3.运用

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>js测试</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no"/>
    <meta name="description" content="my fortune" />
    <style>        
        html {
            font-size: 24px!important;
            padding-bottom: 0;
        }        
    </style>
</head>
 <body>
    <div id="ajax">
        
    </div>
    <script src="./ajax.js"></script>    
    <script type="text/javascript">
        var country = "US";
        var lan = "en";
        var news_url = "https://contentapi.celltick.com/mediaApi/v1.0/notification";
        ajax({
            method: "GET",
            data: {
                publisherId: "ZTE-Push",
                key: "ZPaP5GSQzmg41tHF0h7Jv0u2SOuH4OM4",
                limit: 10,
                userId: "572776656",
                countryCode: country,
                lanuguage: lan

            },
            url: news_url,
            success: function(response) {
                //console.log(response);
                document.getElementById("ajax").innerHTML=response;
            },
            error: function(e) {
                console.log(e);
            }
        });

    </script>

    <script src="./ajax.fn.js"></script>
    <script type="text/javascript">
        umeAjax.ajax({
            method: "GET",
            data: {
                publisherId: "ZTE-Push",
                key: "ZPaP5GSQzmg41tHF0h7Jv0u2SOuH4OM4",
                limit: 10,
                userId: "572776656",
                countryCode: country,
                lanuguage: lan

            },
            url: news_url,
            success: function(response) {
                console.log("umeAjax: "+response.length);
            },
            error: function(e) {
                console.log(e);
            }
        });

        var getAdUrl = "http://browser.umeweb.com/cn_ume_api/ads/api/request"; //ajax参数

        umeAjax.ajax({
            method: 'POST',
            url: getAdUrl,
            contentType: "application/json;charset=utf-8",
            data:{
                "app": {
                    "sdk_channel": "",
                    "app_id": "",
                    "app_version": "",
                    "app_package": ""
                },
                "addes": [{
                    "ad_type": 2,
                    "impression_num": 3,
                    "ad_slot": 2,
                    "ad_width": 0,
                    "ad_height": 0
                }],
                "device": {
                    "screen_width": 1280,
                    "screen_height": 720,
                    "os_type": 2,
                    "imei": "864783024054476",
                    "device_type": 2,
                    "androidid": "f58d85c248c37836",
                    "model": "HLANOTE1-L",
                    "os_version": "",
                    "hardware": "mt6752",
                    "display": "HLANOTE1-L-V1.0",
                    "total_rom": "3047200",
                    "board": "techain6752_lt_kk",
                    "total_ram": "1961972",
                    "product": "HLANOTE1-L",
                    "manufacturer": "YUSUN",
                    "device": "HLANOTE1-L",
                    "brand": "YUSUN",
                    "mac": "e8:92:a4:99:6f:00"
                },
                "user": {
                    "ip": "115.239.210.20",
                    "uid": "",
                    "imsi": "460016131813183",
                    "networktype": 1,
                    "lang": "zh_CN"
                } 
            },
            dataType: 'json',
            success: function(data) {
                var obj = JSON.parse(data);
                if (obj.retcode == "0" && obj.ads.length > 0) {
                    console.info("广告API要求胜利:"+ JSON.stringify(obj));
                } else {
                    console.info("要求胜利,数据非常 :"+ JSON.stringify(obj));
                }
            },
            fail: function(e) {
                console.info("要求毛病,毛病信息:"+e);
            }
        });

    </script>
        
</body> 
</html>

4.拓展
封装post体式格局的promise的ajax插件


/*
*promise
* 用Promise封装一个post要求的要领
*/
function postJSON(url, data) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-type", "application/json;charset=utf-8");

        xhr.onreadystatechange = function() {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(JSON.parse(this.responseText), this);
                    //debug_print("ajaxPromise(param) success: " +this.responseText);
                } else {
                    var resJson = {
                        code: this.status,
                        response: this.response
                    };
                    reject(resJson, this);
                }
            }
        };
        xhr.send(JSON.stringify(data));
    });
}

// 用Promise封装一个get要求的要领,基于ajax
function ajaxPromise(param) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: param.url,
            type: 'get',
            data: param.data || '',
            success: function (data) {
                //console.info(data);
                debug_print("ajaxPromise(param) success: " + JSON.stringify(data));
                resolve(data);
            },
            error: function (error) {
                //console.info(error);
                debug_print("ajaxPromise(param) error: " + JSON.stringify(error));
                reject(error)
            }
        });
    });
}
    原文作者:Linda0821
    原文地址: https://segmentfault.com/a/1190000018011350
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞