封装的ajax请求

在做登录注册这类提交表单数据时,我们经常需要局部刷新网页来验证用户输入的信息,这就需要用到ajax请求,我们通常需要获取表单中的数据,发起ajax请求,通过服务程序,与数据库的数据进行比对,判断信息的正确与否。这儿也将ajax请求进行了封装,当我们在项目中需要多次ajax请求时,就可以用封装的函数了,不用每次都写ajax请求,提高了代码的利用率和工作效率。当然封装得不一定很完美,网上也有很多优秀的封装好的ajax请求。也是通过闭包思想,具体的封装思路,在代码注释中也写得很详细了

这是封装的ajax请求

var dajax=function(){
        function createAjax(){
            //创建XHR对象
           var xhr;
            if(window.XMLHttpRequest){
                xhr=new XMLHttpRequest();
            }
            else if(window.ActiveXObject){
                xhr=new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xhr;
        }
        //ajax请求
        function ajaxRequest(obj){
            /*
             * success:成功时的处理
             * asyn:同步还是异步
             * method:get还是post方式
             * url:地址(路径)
             * */
            //XHR请求
//            var xhr=createAjax();//执行创建XHR对象
            //xhttpr=xhr;
            var xhr=obj.xhr;//用xhr接收传入的变量名,此xhr与createAjax()中的xhr不同
            xhr.onreadystatechange=obj.success;
            if(obj.asyn=="undefined"){
                obj.asyn=true;//异步
            }
            var ddParam=[];//定义一个数组,用来存放ajax请求传递的参数
            for(key in obj.param){
                ddParam.push(key+"="+obj.param[key]);
            }
            var dataParam=ddParam.join("&");//多个参数之间用&分割
            //console.log(dataParam);
            if(obj.method=="get"){
                //obj.url=obj.url+"?username="+obj.param[0];//param[0]+&param[1]
                obj.url=obj.url+"?"+dataParam;
                xhr.open(obj.method,obj.url,obj.asyn);
                xhr.send(null);
            }
            if(obj.method=="post"){
                xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xhr.open(obj.method,obj.url,obj.asyn);
                xhr.send(dataParam);
            }
        }
        //返回ajaxRequest()方法
        return myAjax={
            ajaxRequest:ajaxRequest,
            createAjax:createAjax
        };
    }

在我们需要发起ajax请求时,则只需要写(这里以登录时,判断用户名或密码是否正确,发起ajax请求为例)

var getAjax=dajax();//封装的ajax方法
    var xhttpr=getAjax.createAjax();//得到创建XHR对象(createAjax())中的xhr,并赋给用自定义的变量,eg:xhttpr
    user.onblur= function () {//例如当登录时,填写用户名,失去焦点时,发送ajax请求,判断是否存在该用户,实现局部刷新
        getAjax.ajaxRequest({
            success:function(){
                //请求成功,用户定义的操作
                if(xhttpr.readyState==4&&xhttpr.status==200){
                if(xhttpr.responseText=='1'){
                    user.nextElementSibling.innerHTML='';
                }
                else{
                    user.nextElementSibling.innerHTML='用户名不存在';
                }
            }
            },
            method:"get",
            url:"checkuser.do",
            param:{
                name1:user.value,
                name2:"pwd"
            },
            xhr:xhttpr   //把用户定义的这个变量名(xhttpr),传到封装的ajax中
        })
    }

至于发起请求后,服务处理,dao层如何处理,这儿就不过多阐释了

原文地址:https://www.cnblogs.com/moqq/p/6135930.html