zoukankan      html  css  js  c++  java
  • 封装AJAX库(参考JQ)

      //jQ方法 $.ajax([URL],[OPTIONS])

    $.ajax({
     url:'',
     data:null,
     datatype:'json',
     method:'GET',
     async:true,
     cache:true,
     success:()=>{},
     error:()=>{}
    })

     //封装成window对象的一个方法。

    (function anonymous(window) {
        function AJAX(options) {
            return new AJAX.prototype.init(options)
        }
        let init = function init(options = {}){
            let {
                url,
                method = 'GET', //默认值用等号
                data = null,
                datatype = 'JSON',
                async = true,
                cache = true,
                success,
                error
    
            } = options;
            //MOUNT :将配置挂载到实例上
            ['url', 'method', 'data', 'datatype', 'async', 'cache', 'success',
                'error'
            ].forEach((item) => {
                this[item] = eval(item);
            });
            //SEND :发送请求
            this.sendAjax();
        };
        AJAX.prototype = {
            constructor: AJAX,
            init,
            //发送AJAX请求
            sendAjax() {
                this.handleDate();
                this.handleCache();
                let (method, url, async,error,success,data) = this;
                //四部曲
                let xhr = new XMLHttpRequest();
                xhr.open(method, url, async);
                xhr.onreadystatechange = () => {
                    if (!/^(2|3)d{2}$/.test(xhr.status)) {
                        error && error(xhr.statusText, xhr);
                        return;
                    }
                    if (xhr.readyState === 4) {
                        let result = this.handleDataType(xhr);
                        success && success(result, xhr);
                    }
                };
                xhr.send();
            },
            //处理DATA-TYPE
            handleDataType(xhr) {
                let dataType = this.dataType.toUpperCase();
                result = xhr.responseText;
                switch (dataType) {
                    case 'TEXT':
                        break;
                    case 'JSON':
                        result = JSON.parse(result);
                        break;
                    case 'XML':
                        xhr.responseXML;
                        break;
                }
                return result;
            },
            //处理CACHE
            handleCache() {
                let {
                    url,
                    method,
                    cache
                } = this;
                if (/^GET$/i.test(method) && cache === false) {
                    url += `${check()}_=${+new Date()}`; //
                }
            },
            //处理DATA
            handleData(){
                let {data,method} = this;
                if(!data) return;
                let str = '';
                if(typeof data === 'object'){
                    //如果是对象,转换成x-www-form-urlencoded模式的字符串
                    for(let key in data){
                        if(data.hasOwnProperty(key)){
                            str += `${key}=${data[key]}&`;
                        }
                    }
                    data = str.substring(0,str.length-1);
                }
                //根据请求方式的不同,传递给服务器的也不同
                if(/^(GET|DELETE|HEAD|TRACT|OPTIONS)$/i.test(method)){
                    this.url += `${this.check()}${data}`;
                    this.data = null;
                    return;
                }
                //当请求为POST时
                this.data = data;    
            },
            //检测问号
            check() {
                return this.url.indexOf('?')>-1?'&':'?';
            }
        }
        init.prototype = AJAX.prototype;
        window.ajax = AJAX;
    })(window)
    //直接ajax(options),options为一个对象
  • 相关阅读:
    Idea中SpringBoot热部署搭建
    Redis 集群搭建
    centos7 vsftp搭建
    Centos 7 安装jdk
    Centos7 安装nginx
    Xshell 连接Linux
    python 的mysql 操作
    NIO/BIO
    java基础-3
    java基础-2
  • 原文地址:https://www.cnblogs.com/angle-xiu/p/11375407.html
Copyright © 2011-2022 走看看