美文网首页
js ajax详解 / ajax封装思路 / ajax实现类似j

js ajax详解 / ajax封装思路 / ajax实现类似j

作者: Peter_2B | 来源:发表于2021-08-26 11:40 被阅读0次
    • js脚本发起HTTP请求必须通过XMLHttpRequest对象,也是通过AJAX进行浏览器与服务器通信的接口,不局限于XML,可以发送任何格式的数据

    • XMLHttpRequest本身是JS引擎内置的构造函数,所有XMLHttpRequest都需要被实例化 new XMLHttpRequest();

    • IE5,6使用ActiveX对象: new ActiveXObject('MicrosoftXMLHTTP')

    参数说明

    var xhr = new window.HMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    
    // console.log(xhr.readyState)      // 0:请求未初始化
    
    // xhr.open('GET', 'http://...?name=tome&password=123', true);
    // xhr.send();
    
    xhr.open('POST', 'http://...', true);
    xhr.setReqeustHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send('name=tom&password=123');
    
    // console.log(xhr.readyState)      // 1:服务器连接已建立
    
    xhr.onreadystatechange = function(){
        // console.log(xhr.readyState) // 2 3 4
        if(xhr.readyState === 4 && xhr.status === 200){
            console.log(JSON.parse(xhr.responseText));
        }
    }
    
    open方法(发送设置)
    xhr.open(method: 请求方式, url: 请求发送的地址, true异步 / false同步 )
    
    xhr.send(发送请求)发送post请求体数据用,GET不填写
    
    xhr.onreadystatechange事件: 挂载到XMLHttpRequest对象上的事件
    xhr.readyState属性: 通过XMLHttpRequest对象发送HTTP请求的各阶段状态码
            0:请求未初始化
            1:服务器连接已建立
            2:请求已接收
            3:请求处理中
            4:请求已完成,且响应已就绪
    
    xhr.status属性: 服务器响应的状态码
            200: 响应成功
            401  请求未携带token/无效/超时
            403  Forbidden 账号权限不够
            404: Not found请求资源不存在 
    
    当readyState变化时,将触发onreadystatechange事件执行其回调函数
    注意: readyState仅仅是针对请求与响应的状态码,获取资源是否成功取决于status状态
    
    xhr.responseText: 获取到JSON类型的字符串数据
    xhr.responseXML: 获取XML数据
    
    POST请求下,send方法的参数格式: name=tom&password=123;
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded);
    POST请求方式必须设置这个请求头信息,目的是将请求体中的数据(name=tom&password=123)转换成键值对,
    这样后端接收到name=tom&password=123这样的数据才知道这是一个POST方式传过来的数据
    

    封装思路: 实现似于jQuery的调用方式

    function $(){
        return {
            a: 1, 
            b: 2
        }
    }
    console.log( $().a )  // $()得到返回的对象,对象.a 获取到1
    
    ---------------------------------------------------------------------
    
    var $ = (function(){
        return {
            a: 1,
            b: 2
        }
    })();
    
    console.log( $.a );   // 1
    

    封装ajax

    var $ = (function(){
                                          // new ActiveXObject用于IE5,6
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    
        if(!xhr){
            throw new Error('您的浏览器不支持异步发起HTTP请求');
        }
    
        function packAjax(options){
            var opt = options || {},
                type = (opt.type || 'GET' ).toUpperCase(),
                async = opt.async || true,   
                url = opt.url,
                data = opt.data || null,
                error = opt.error || function(){},       // 失败执行的函数
                success = opt.success || function(){},   // 成功执行的函数
                complete = opt.complete || function(){}; // 不管成功or失败都会执行的函数
    
            if(!url){
                throw new Error('您没有填写URL');
            }
    
            xhr.open(type, url, async);
    
            if(type==='POST'){
                xhr.setReqeustHeader('Content-type', 'application/x-www-form-urlencoded');
            }
    
            xhr.send(type === 'GET' ? null: formatDatas(data));  // get请求方式send()传空;
    
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4 && xhr.status === 200){
                    success(JSON.parse(xhr.responseText));
                    complete();
                }
    
                if(xhr.status === 404){
                    error();
                    complete();
                }
            }
        }
    
        function formatDatas(obj){
            var str = '';
            for(var key in obj){
                str += 'key'+'='+obj[key]+'&';
            }
            str.replace(/&$/,'');      // 最后多一个&, &结尾替换空字符
            return str;                // name=tom&password=123
        }
    
        return {
            ajax: function(options){
                packAjax(options);
            },
            post: function(url, data, callback){
                packAjax({
                    type:'POST',
                    url,
                    data,
                    success:callback
                })
            },
            get: function(url,callback){
                packAjax({
                    type: 'GET',
                    url,
                    success: callback
                })
            }
        }
    
    })();
    
    
    // $.ajax({
    //     type: 'POST',
    //     url:'http://....',
    //     data: {
    //         name: 'tom',
    //         password: 123
    //     },
    //     success:function(res){
    //         console.log(res);
    //     }
    // })
    
    // $.post({
    //     url:'http://....',
    //     data: {
    //         name: 'tom',
    //         password: 123
    //     },
    //     success:function(res){
    //         console.log(res);
    //     }
    // })
    
    $.get({
        url:'http://....?name=tom?password=123',
        success:function(res){
            console.log(res);
        }
    })
    

    相关文章

      网友评论

          本文标题:js ajax详解 / ajax封装思路 / ajax实现类似j

          本文链接:https://www.haomeiwen.com/subject/zdgyiltx.html