zoukankan      html  css  js  c++  java
  • javascript 封装ajax(多版本)

    javascript 封装ajax(多版本)

    版本一(推荐的写法)

    ajax的过程

    1.创建XMLHttpRequest对象,也就是创建一个异步调用对象。

    2.创建一个新的Http请求,并制定该Http请求的方法,url以及验证信息。

    3.设置响应http请求状态的变化。

    4.发送http请求。

    5.获取异步调用返回的数据。

    6.利用javascript或者dom实现局部刷新操作。

     var AjaxUtil={
          //基础选项
          options:{
               method:"get",
               url:"",
               params:{},
               type:"text", // xml json
               callback:function() {
                   
               }  
          },//创建xmlHTTPrequest对象;
          createRequest:function (){
          var xmlhttp;
          try{
                 xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");  
          }catch(e){
              try{
                  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  
              }catch(e){
               try{
                   xmlhttp=new XMLHttpRequest();
                   if(xmlhttp.overrideMimeType){
                      xmlhttp.overrideMimeType("text/xml");
                   }
               }catch(e){
                  alert('你额浏览器不支持Ajax');   
               }
              }
            }
           return xmlhttp;
         },//设置基础选项;
         setOptions:function(newOptions){
            for(var pro in newOptions){
              this.options[pro]=newOptions[pro];    
            }
         },//格式化参数
         formateParameters:function (){
             var paramsArray=[];
             var params=this.options.params;
             for(var pro in params){
                 var paramValue=params[pro];
                 if(this.options.method.toUpperCase()==="GET"){
                    paramValue=encodeURIComponent(params[pro]); 
                 }
                 paramsArray.push(pro+'='+paramValue);
             }
             return paramsArray.join('&');
          },//状态改变的处理滴
          readystatechange:function (xmlhttp){
            var returnValue;
            if(xmlhttp.readyState==4 && (xmlhttp.status==200)){
              switch(this.options.type){
                 case 'xml':
                 returnValue=xmlhttp.responseXML;
                 break;
                 case 'json':
                 var jsonText=xmlhttp.responseText;
                 if(jsonText){
                   returnValue = eval("(" + jsonText + ")");
                 }
                 break;
                 default:
                 returnValue=xmlhttp.responseText;
                 break;
              }
           if(returnValue){
                  this.options.callback.call(this,returnValue); 
            }else{
                    this.options.callback.call(this);
                 }
            }
          },//发送ajax请求
          request:function(options){
             var ajaxObj=this;
             //设置参数
             ajaxObj.setOptions.call(ajaxObj,options);
             //创建XMLHTTPRequest对象
             var xmlhttp=ajaxObj.createRequest.call(ajaxObj);
             //设置回调函数;
             xmlhttp.onreadystatechange=function (){
                ajaxObj.readystatechange.call(ajaxObj,xmlhttp); 
             }
             //格式化参数
             var formateParams=ajaxObj.formateParameters.call(ajaxObj);
             //请求方式
             var method=ajaxObj.options.method;
             var url=ajaxObj.options.url;
             
             if("GET"===method.toUpperCase()){
                 if(formateParams){
                   url+="?"+formateParams+"random="+Math.random();//使用get的方式容易出现缓存的干扰滴呀
                 }else{  //这里应该考虑考虑到缓存的问题
                  url+='?random='+Math.random();
                 }
             }
             //建立连接;
             xmlhttp.open(method,url,true);
             
             if("GET"===method.toUpperCase()){
                xmlhttp.send(null); 
             }else if("POST"==method.toUpperCase()){
                xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                xmlhttp.send(formateParams);
             }
             
          }
       }
       
       function test(){
          AjaxUtil.request({
             method:'get',
             url:'data/json.txt',
             type:"json",
             callback:function (json){
                 alert(json.name);
             }
              
          })
       }

    版本二

      这个方法没有前面的封装的好,单也可以用来练练手滴呀

      

       function createXHR(){
         if(typeof XMLHttpRequest !="undefined"){  //非IE6浏览器
            return new XMLHttpRequest(); 
         }else if(typeof ActiveXObject !='undefined'){
            var version=[
                  "MSXML2.XMLHttp.6.0",
                  "MSXML2.XMLHttp.3.0",
                  "MSXML2.XMLHttp"
            ];
            for(var i=0;i<version.length;i++){
               try{
                 return new ActiveXObject(version[i]);   
               }catch(e){
                 
               }
            }
         } else{
             throw new Error("你的系统部或浏览器不止XHR对象");
         }
       }
      
      //转义字符
      function params(data){
         var arr=[];
         for(var i in data){
            arr.push(encodeURIComponent(i)+"="+encodeURIComponent(data[i])); 
         }
         return arr.join("&");
      }
      //封装ajax
      function show_ajax(obj){
        var xhr=createXHR();
        obj.url=obj.url+"?random="+Math.random();//主要用来清楚缓存
        obj.data=params(obj.data);
        if(obj.method.toUpperCase()==="GET"){
          obj.url+=(obj.url.indexOf("?")==-1)?"?"+obj.data:"&"+obj.data;
        }
        //异步
        if(obj.async===true){
         xhr.onreadystatechange=function (){
            //执行完成
            if(xhr.readState==4){
              callBack();
            }
         }
        }
         xhr.open(obj.method,obj.url,obj.async);
        if(obj.method.toUpperCase()==="POST"){
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xhr.send(obj.data);
        }else{
          xhr.send(null);    
        }
        if (obj.async==false){
            callBack();
        }
        function callBack(){
          //
          if(xhr.status==200){
              obj.success(xhr.responseText)
          }else{
             obj.Error("获取数据失败"+xhr.status);
          }
        }
      }
      function testInfo(){
          show_ajax({
            "method":"get",
            "url":"",
            "success":function (data){
            
            },
            "Error":function (data){
            
            },
            "async":false
          })
      }
  • 相关阅读:
    linux系统备份
    VNC轻松连接远程Linux桌面
    Cacti监控服务器配置教程(基于CentOS+Nginx+MySQL+PHP环境搭建)
    Linux tar命令高级用法——备份数据
    在linux下使用debugfs恢复rm删除的文件
    Linux系统MySQL开启远程连接
    查看LINUX进程内存占用情况
    JavaScript使用数组
    JavaScript计时器
    大话三层架构
  • 原文地址:https://www.cnblogs.com/mc67/p/5238386.html
Copyright © 2011-2022 走看看