笔记:JS常用utils

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <style type="text/css">

    </style>
</head>
<script type="text/javascript">
    function MFPageTool() {
        /*设置cookie*/
        this.setCookie = function (c_name, value, expire) {
            var date = new Date();
            date.setDate(date.getDate() + expire)
            document.cookie = c_name + "=" + escape(value) + "; expires=" + date.toGMTString();
        }
        /*获取cookie*/
        this.getCookie = function (c_name) {
            if (document.cookie.length > 0) {
                let c_start = document.cookie.indexOf(c_name + "=");
                if (c_start != -1) {
                    c_start = c_start + c_name.length + 1;
                    let c_end = document.cookie.indexOf(";", c_start);
                    if (c_end == -1)
                        c_end = document.cookie.length;
                    return unescape(document.cookie.substring(c_start, c_end));
                }
            }
            return "";
        }
        /*删除cookie*/
        this.delCookie = function (c_name) {
            setCookie(c_name, "", -1);
        }
        /* 封装ajax函数
         * @param {string}opt.type http连接的方式,包括POST和GET两种方式
         * @param {string}opt.url 发送请求的url
         * @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
         * @param {object}opt.data 发送的参数,格式为对象类型
         * @param {function}opt.success ajax发送并接收成功调用的回调函数
         */
        this.Ajax = function (opt) {
            opt = opt || {};
            opt.method = opt.method.toUpperCase() || 'POST';
            opt.url = opt.url || '';
            opt.async = opt.async || true;
            opt.data = opt.data || null;
            opt.success = opt.success || function () {};
            opt.error = opt.error || function () {};
            var xmlHttp = null;
            if (XMLHttpRequest) {
                xmlHttp = new XMLHttpRequest();
            } else {
                xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
            }
            var params = [];
            for (var key in opt.data) {
                params.push(key + '=' + opt.data[key]);
            }
            var postData = params.join('&');
            if (opt.method.toUpperCase() === 'POST') {
                xmlHttp.open(opt.method, opt.url, opt.async);
                xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
                xmlHttp.send(postData);
            } else if (opt.method.toUpperCase() === 'GET') {
                xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
                xmlHttp.send(null);
            }
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    opt.success(JSON.parse(xmlHttp.responseText));
                } else {
                    opt.error(JSON.parse(xmlHttp.responseText));
                }
            };
        }
        /** 截取地址栏参数 */
        this.GetRequest = function () {
            var url = decodeURI(location.href); //获取url中"?"符后的字串
            console.log(location);
            var theRequest = new Object();
            var index = url.indexOf("?");
            if (index != -1) {
                var str = url.substr(index + 1);
                var strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }
        // 对Date的扩展,将 Date 转化为指定格式的String
        // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
        // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
        // 例子: 
        // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
        // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
        this.dateFormat = function (date, fmt) { //author: meizz 
            var _fmt = fmt || "yyyy-M-d h:m:s.S";
            var o = {
                "M+": date.getMonth() + 1, //月份 
                "d+": date.getDate(), //日 
                "h+": date.getHours(), //小时 
                "m+": date.getMinutes(), //分 
                "s+": date.getSeconds(), //秒 
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
                "S": date.getMilliseconds() //毫秒 
            };
            if (/(y+)/.test(_fmt)) _fmt = _fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1
                .length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(_fmt)) _fmt = _fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ?
                    (o[
                        k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return _fmt;
        }
    };
</script>

<body>
    <div class="textWarp">
        <button onclick="testFn()">发起请求</button>
        <div id="count">接口耗时:0 秒</div>
        <pre id="res">接口返回值:</pre>
    </div>
</body>
<script>
    function testFn() {
        console.log("发起请求,定时器启动!");
        var count = 0;
        var timer = setInterval(() => {
            count++;
            document.getElementById("count").innerHTML = "接口耗时:" + count + " 秒";
        }, 1000)
        var pageTool = new MFPageTool();
        var host = "http://192.168.0.78:8082";
        var obj = {
            name: "王港",
            value: "测试",
            expire: "内容"
        };
        pageTool.Ajax({
            method: 'POST',
            url: host + '/welcome',
            data: obj,
            success: function (response) {
                console.log("/stat/setCookie-response: ", response);
                clearInterval(timer);
                count = 0;
                document.getElementById("res").innerHTML = "接口返回值:" + JSON.stringify(response);
            },
            error: function (error) {
                console.log("/stat/setCookie-error: ", error);
                clearInterval(timer);
                count = 0;
                document.getElementById("res").innerHTML = "接口返回值:" + JSON.stringify(response);
            }
        });
    }
</script>

</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值