AJAX封装

AJAX

是异步向服务器请求数据,实现不刷新浏览器更新数据

组成

异步的JS
xhr对象
其他JS
服务器的数据

AJAX特点

提高了页面渲染速度
提高了用户体验
不需要插件支持

缺点

1.破坏了浏览器前进和后退机制(因为ajax自动更新机制
2.一个Ajax请求多了,也会出现页面加载慢的情况。
3.搜索引擎的支持程度比较低。
4.ajax的安全性问题不太好(可以用数据加密解决)。

AJAX的基本过程

使用ajax一共有4个步骤:1.创建ajax、2.连接服务器、3.发送请求、4.接受返回值。

HTTP请求

HTTP请求有两种方式

GET:用于获取数据,GET是在URL上传递数据(网址后面的东西),存储量较少,安全系数比较低。
POST:用于上传数据,POST安全性一般比(GET好一些),容量几乎是无限(多用于表单)。

AJAX GET请求 过程的简单封装




    
    
    
    Document


    
    
    
    



AJAX POST请求 过程的简单封装




    
    
    
    Document


    
    
    
    



AJAX GET 和 POST 二合一的封装

// 1.预设函数的执行方式,和要传入的参数,及要实现的功能
// ajax({
//     type:"get",             //可选,默认get
//     url:"",                 //必选
//     success:function(){},   //必选
//     error:function(){},     //可选,默认不处理
//     data:{}                 //可选,默认不发
// })

function ajax(options){
    // 2.解析参数,处理默认参数
    let {type,url,success,error,data} = options;
    type = type || "get";
    data = data || {};
    // 3.解析要发送的数据
    var str = "";
    for(var i in data){
        str += `${i}=${data[i]}&`;
    }
    // 4.根据发送方式处理url
    if(type == "get"){
        var d = new Date();
        url = url + "?" + str + "sjc=" + d.getTime();
    }
    // 5.开启ajax
    var xhr = new XMLHttpRequest();
    xhr.open(type,url,true);
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            success(xhr.responseText);
        }else if(xhr.readyState == 4 && xhr.status != 200){
            // 6.首先保证ajax的过程结束了,如果http给失败,才是真正的失败
            error && error(xhr.status);
            // if(error) error(xhr.status);
        }
    }
    // 7.根据发送方式,决定发送的信息
    if(type == "get"){
        xhr.send()
    }else if(type == "post"){
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send(str.slice(0,str.length-1));
    }
}

AJAX GET/POST 和Jsonp三合一封装

// 1.预设函数的执行方式,和要传入的参数,及要实现的功能
// ajax({
//     type:"get",             //可选,默认get
//     url:"",                 //必选
//     success:function(){},   //必选
//     error:function(){},     //可选,默认不处理
//     data:{}                 //可选,默认不发
//     timeout:毫秒数           //可选,默认500,延迟时间,超出时间就出错误,用在jsonp身上
// })

function ajax(options){
    // 2.解析参数,处理默认参数
    let {type,url,success,error,data,timeout} = options;
    type = type || "get";
    data = data || {};
    timeout = timeout || 500;
    // 3.解析要发送的数据
    var str = "";
    for(var i in data){
        str += `${i}=${data[i]}&`;
    }
    // 4.根据发送方式处理url
    // Jsonp1.处理url和数据
    if(type == "get" || type == "jsonp"){
        var d = new Date();
        url = url + "?" + str + "sjc=" + d.getTime();
    }
    
    // Jsonp2.区分jsonp和ajax的功能
    if(type === "jsonp"){
        var script = document.createElement("script");
        script.src = url;
        document.body.appendChild(script);

        window[data[data.columnName]] = function(res){
            success && success(res);
            error = null;
        }
        
        // Jsonp3.jsonp的失败(超时)
        setTimeout(() => {
            error && error("timeout");
            success = null;
        }, timeout);
    }else{
        // 5.开启ajax
        var xhr = new XMLHttpRequest();
        xhr.open(type,url,true);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                success(xhr.responseText);
            }else if(xhr.readyState == 4 && xhr.status != 200){
                // 6.ajax执行成功 但网络出错 才报错
                error && error(xhr.status);
                // if(error) error(xhr.status);
            }
        }
        // 7.根据发送方式,决定发送的信息
        if(type == "get"){
            xhr.send()
        }else if(type == "post"){
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xhr.send(str.slice(0,str.length-1));//去掉多余的&
        }
    }
}

AJAX GET/POST 和Jsonp三合一封装的调用

ajax({
    type:"get",             //可选,默认get
    url:"",                 //必选
    success:function(){},   //必选
    error:function(){},     //可选,默认不处理
    data:{}                 //可选,默认不发
    timeout:毫秒数           //可选,默认500,延迟时间,超出时间,出错误,用在jsonp身上
})

你可能感兴趣的:(AJAX封装)