封装的套路:
1.写一个相对比较完善的用例
2.写一个空函数,没有形参,将刚刚的用例直接作为函数的函数体
3.根据使用过程中的需求抽象函数
代码记录如下:
<script>
        function ajax (method,url,params,done) {
        
            method=method.toUpperCase();
            var xhr=new XMLHttpRequest();
            var tempArr=[];
            if (typeof params=== ‘object‘) {
                for(var key in params){
                    var value = params[key];
                    tempArr.push(key+‘=‘+value);
                }
                params=tempArr.join(‘&‘);
            }    
            if (method===‘GET‘) {
                url+=‘?‘+params;
            }
            xhr.open(method,url);
            var data=null;
            if (method===‘POST‘) {
                xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘);
                data=params;
            }
            params=params || null;
            xhr.send(data);
            xhr.onreadystatechange=function () {
                if (this.readyState!==4) return;
                //reurn 无法再内部包含的函数中通过return给外部函数的调用返回结果
                //由于异步模式下,这里的代码最后执行,所以不可能在外部通过返回的方法
                done(this.responseText);
            }
            
        }
        ajax(‘POST‘,‘add.php‘,{key1 : ‘value1‘,key2: ‘value2‘},function (res){
            console.log(res);
        });
    
    </script>
暂时写到这里~
原文:https://www.cnblogs.com/Yaucheun/p/10487903.html