当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Ajax的原理及封装

Ajax的原理及封装

2020年03月31日  | 移动技术网IT编程  | 我要评论

了解ajax

  • 就是js这个语言和服务端交互的手段
  • 无刷新的页面请求处理
  • 区分表单提交

ajax
即“asynchronous javascript and xml”(异步 javascript 和 xml),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

发送一个ajax请求

四个步骤:

  1. 创建ajax对象
var xhr = new xmlhttprequest();
  1. 配置请求信息
xhr.open('get','./01_data.php',true);
//xhr.open("请求方式","请求地址")
//请求地址: 相对路径
//          绝对路径  http://  https:// ===> 开发中比较常用的方式
  1. 发送请求
xhr.send(null);
  1. 接受响应
// 用事件接收 level1 => 原始版本的ajax  ,  level2 => 进阶版本的ajax
// readystate  ajax状态码 
// change 改变
// 事件可能触发 3-4 次
// 状态码有5个  0 1 2 3 4
// 4表示成功
xhr.onreadystatechange = function(){
    // 只要判定状态即可,其他的情况不考虑
    if( xhr.readystate === 4){
        console.log(xhr.responsetext)
    }
}

ajax状态码

ajax的状态码 有5个 : 0 1 2 3 4

  • 0:创建ajax对象成功
  • 1:配置请求信息成功
  • 2:响应已经回到浏览器
  • 3:浏览器正在解析响应体
  • 4:响应体解析完毕可以使用了

ajax的兼容处理

  • 1.创建ajax对象
var xhr = null;
    if(typeof xmlhttprequest === "function"){
        xhr = new xmlhttprequest();
    }else{
        xhr = new activexobject("microsoft.xmlhttp");
    }
  • 2.发送请求
xhr.onreadystatechange = function(){
        if(xhr.readystate === 4 && /^2\d{2}$/.test(xhr.status)){
            console.log(xhr.responsetext);
        }
    }

封装ajax操作

ajax是异步程序,我们什么时候可以使用ajax加载回来的数据?

// ajax 兼容性良好的封装;
function ajax( options ){
    // 默认参数;
    var _default = {
        type : "get",
        url : "",
        data : null,
        // 返回的数据类型;
        datatype : "text",
        status : null,
        success : function(){},
        complete : function(){},
        error : function(){}
    }
    // 我们会创建一些默认参数, 如果用户传入了其他数据会对默认参数进行覆盖;
    options = assign( _default , options );
    options.type = options.type.tolowercase();
    // 如果存在context;
    if( isobject(options.context) ){
        var callback_list = ["success","complete","error"];
        // 如果老版本浏览器更新成for循环;
        callback_list.foreach( function( item ){
            // console.log(options[item]);
            options[item] = options[item].bind( options.context );
        })
    }
    // 1. 创建xhr ;
    
    //创建ajax对象的兼容
    var xhr = null;
    if(typeof xmlhttprequest === "function"){
        xhr = new xmlhttprequest();
    }else{
        xhr = new activexobject("microsoft.xmlhttp");
    }
    
    // 可以简化;
    // 1. 如果请求方式为get,那么我们把数据拼接到url上;
    if(options.type === "get"){
        options.url =  tourldata( options.data , options.url , options.type)
    }
    // 2. 如果请求方式为post,那么我们把数据拼接到data上;
    if(options.type === "post"){
        options.data =  tourldata( options.data , options.url , options.type)
    }
    
    // 2. 根据数据进行方法的调用;
    xhr.open( options.type , options.url , true ) ;
    options.type === "post" ? xhr.setrequestheader("content-type","application/x-www-form-urlencoded") : "";
    // 3. 调用send方法;
    xhr.send( options.type=== "get" ? null : options.data );
    // 4. 调用回调函数;
    xhr.onreadystatechange = function(){
        // xhr程序运行结束;
        if( xhr.readystate === 4 ){
            options.complete();
            
            if( /^2\d{2}$/.test(xhr.status) ){
                // 5.传递数据
                // 如果需要转换成json那么我们就返回json,如果不需要原样返回;
                // 如果json.parse报错了那么我们要调用错误函数;
                try{
                    var res = options.datatype === "json" ? json.parse(xhr.responsetext) : xhr.responsetext; 
                    options.success(res);
                }catch(e){
                    options.error(e,xhr.status);
                }
            }else{
                options.error("error",xhr.status);
            }
            // 策略模式调用 : 
            if( isobject(options.status) ){
                typeof options.status[xhr.status] === "function" ? options.status[xhr.status]() : "";
            }
        }
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网