ajax原理及封装

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

ajax原理及封装

小峰子926   2020-03-29 我要评论

一:AJAX 简介

       AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术,通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。

       AJAX = 异步 JavaScript 和 XML。

二:AJAX的使用
      1.创建ajax对象:

                                const xhr = new XMLHttpRequest();// IE9及以上
                                const xhr = new ActiveXObject('Mricosoft.XMLHTTP');// IE9以下

      2.配置请求信息:

                                xhr.open('请求方式', '请求地址', 是否异步);

                                请求方式 get / post / put / ...;请求地址 url;默认true表示异步,false表示同步。

      3.发送请求:

                                xhr.send();

      4.接收响应:

                        xhr.onload = function () { console.log(xhr.responseText) };

             xhr.onreadyStateChange = function () {if (xhr.readyState === 4 && /^2\d{2|$/.test(xhr.status)) {}};其中readyState表示状态码,为4即表示成功;stauts是http状态码,2系列都表示成功;

三:AJAX封装

  1.兼容处理:

  创建ajax对象兼容

        var xhr = null;
        if(typeof XMLHttpRequest === "function"){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }

  2.代码封装

         function assign(){
            var target = arguments[0];
            for(var i = 1 ; i < arguments.length ; i ++){
                // console.log(arguments[i]);
                for(var attr in arguments[i]){
                    target[attr] = arguments[i][attr];
                }
            }
            return target;
        }

        function toUrlData( obj , url , method){
            if( isObject(obj) ){
                var str = "";
                for(var attr in obj){
                    str += "&" + attr + "=" + obj[attr]
                }
                str = str.slice(1);
                // 如果数据发送方式是POST,那么直接返回str就可以了;
                method = method || "";
                if( method.toUpperCase() === "POST"){
                    return str;
                }
                url += "?" + str;
                return url;
            }
            return url;
        }
        function isObject( data ){
            return (typeof data === "object" && data !== null && data.constructor && data.constructor === Object)
        }     
        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();

            if( isObject(options.context) ){
                var callback_list = ["success","complete","error"];
                callback_list.forEach( function( item ){
                    // console.log(options[item]);
                    options[item] = options[item].bind( options.context );
                })
            }
            
            // 1. 创建shr ;
            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.传递数据

                        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]() : "";
                    }
                }
            }
        }

 

 

                     

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们