打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Ajax的原理及封装

了解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]() : "";
            }
        }
    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
重拾Ajax | Aitter's Blog
javascript使用ajax请求具体步骤
逐渐深入地理解Ajax
解读Ajax原理是什么?如何实现?
Ajax GET请求应用
控制台测试ajax
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服