试试自行封装AJAX和jQuery中的ajax封装的基本使用

封装的套路:

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>

jQuery中ajax的基本使用

<script src="jq-1.12.4.js"></script>
    <script>
        $.ajax({
            url: 'add.php',
            type: 'POST',  //methor 请求方法
            success : function(res){
                console.log(res);  //拿到的是响应体
            },
             dataType: 'json',
            data: {id: 1, name:'张三'}
        });
        
        
    </script>

 jQuery中ajax的回调函数使用

<script src="jq-1.12.4.js"></script>
    <script>
        $.ajax({
            url: 'add.php',
            type: 'POST',
        beforeSend: function (xhr){
            //在所有的发送请求的操作之前执行
            console.log('beforeSend',xhr);
        },
        success: function(res){
            //隐藏loading
            //只有请求成功(状态码为200)才会执行这个函数
            console.log(res);
        },
    
        error:(function(xhr) {
            //隐藏loading
            //只有请求不正常(状态码不为200)才会执行这个函数
            console.log("error");
        }),
        complete:(function(xhr) {
            //不管成功还是失败都会执行这个函数
            console.log("complete");
        })
            });



    </script>

 

posted @ 2019-03-07 10:22  YauCheun  阅读(402)  评论(0编辑  收藏  举报