码迷,mamicode.com
首页 > Web开发 > 详细

Ajax

时间:2020-03-29 19:39:03      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:sign   cat   XML   区别   else   typeof   php   中文   lse   

Ajax的全称是Asynchronous JavaScript and XML 中文名称定义为异步的JavaScript和XML,Ajax是一种用于创建快速动态网页的技术。以前网页需要更新网页内容则需要重载页面,而使用Ajax可以让网页实现异步更新即可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

Ajax的工作原理是:客户端发送请求,请求交给xhr,从而把请求提交给服务器,服务器进行业务处理,把响应数据交给xhr对象,xhr对象接收数据,最后javascript把数据写到页面上。

Ajax的实现步骤:

1. 创建 ajax 对象

let xhr = new XMLHttpRequest()

2. 配置请求信息

xhr.open(‘GET’, ‘./test.php’, true)

3. 发送请求

xhr.send()

4. 接受响应

xhr.onload = function () {

  console.log(xhr.responseText)

}

Ajax的封装:

Ajax的封装需要考虑两种请求方式即为GET和POST,还要考虑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"];

                callback_list.forEach( function( item ){

                    options[item] = options[item].bind( options.context );

                })

            }          

            // 1. 创建shr ;

            var xhr = null;

            //创建 ajax对象 的兼容

            if(typeof XMLHttpRequest === "function"){

                xhr = new XMLHttpRequest();

            }else{

                xhr = new ActiveXObject("Microsoft.XMLHTTP");

            }

            //区别请求方式

            if(options.type === "get"){

                options.url =  toUrlData( options.data , options.url , options.type)

            }

            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(){

                //接受响应的兼容

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

                    }

                }

            }

        }

导入的方法具体代码如下:

    function toUrlData( obj , url , method){

            if( isObject(obj) ){

                var str = "";

                for(var attr in obj){

                    str += "&" + attr + "=" + obj[attr]

                }

                str = str.slice(1);

                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)

        }

Ajax

标签:sign   cat   XML   区别   else   typeof   php   中文   lse   

原文地址:https://www.cnblogs.com/bxf1245/p/12594098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!