ajax基础(2)封装

简单封装1

function ajax(method,url,data,success) {
    var xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (method == 'get' && data) {
        url+='?'+data;
    }

    xhr.open(method,url,true);

    if (method == 'get') {
        xhr.send();
    }else {
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
        xhr.send(data)
    }


    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                success && success(xhr.responseText);
                // console.log(xhr.responseText)
            }else{
                alert('出错了: '+xhr.status )
            }
        };
    }
}

简单封装2

//method,url,opts,success
function ajax(opts) {
    var xhr = null;
    var options = {
        method : 'GET',
        url : '',
        data : '',
        async : true,
        timeout : function(){},
        success : function(){},
        error : function(){}
    }
    for(var key in opts){
        options[key] = opts[key]
    }
    if (window.XMLHttpRequest) {
        xhr = new  XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (options.method.toUpperCase() == 'GET'&& options.data) {
        var empty = '';
        for(var key in options.data ){  //options.data {'name' : 'bob', 'age' : 67}
            empty += encodeURI(key)+'='+encodeURI(options.data[key])+'&';
        }
        options.url+='?'+empty+new Date().getTime();

    };
    xhr.open(options.method,options.url,options.async);

    if (options.method.toUpperCase() == 'GET') {
        xhr.send();
    }else{
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var data='';
        for(var key in options.data){
            data += key +'='+options.data[key]+'&';
        }
        data.slice(0,-1)
        xhr.send(data);
    }



    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                // alert(xhr.responseText)
                options.success && options.success(xhr.responseText);
            }else {
                alert('出错了:' + xhr.status)
            }
        };
    }
}

简单封装3 转载别人的

原文地址

/*
  *author: Ivan
  *date: 2014.06.01
  *参数说明:
  *opts: {'可选参数'}
  **method: 请求方式:GET/POST,默认值:'GET';
  **url:    发送请求的地址, 默认值: 当前页地址;
  **data: string,json;
  **async: 是否异步:true/false,默认值:true;
  **cache: 是否缓存:true/false,默认值:true;
  **contentType: HTTP头信息,默认值:'application/x-www-form-urlencoded';
  **success: 请求成功后的回调函数;
  **error: 请求失败后的回调函数;
 */
 function ajax(opts){
     //一.设置默认参数
     var defaults = {    
             method: 'GET',
                url: '',
               data: '',        
              async: true,
              cache: true,
        contentType: 'application/x-www-form-urlencoded',
            success: function (){},
              error: function (){}
         };    

     //二.用户参数覆盖默认参数    
     for(var key in opts){
         defaults[key] = opts[key];
     }

     //三.对数据进行处理
     if(typeof defaults.data === 'object'){    //处理 data
         var str = '';
         for(var key in defaults.data){
             str += key + '=' + encodeURI(defaults.data[key]) + '&';
         }
         defaults.data = str.substring(0, str.length - 1);
     }

     defaults.method = defaults.method.toUpperCase();    //处理 method

     defaults.cache = defaults.cache ? '' : '&' + new Date().getTime() ;//处理 cache

     if(defaults.method === 'GET' && (defaults.data || defaults.cache))   {
        defaults.url += '?' + defaults.data + defaults.cache;    //处理 url 
     }    

     //四.开始编写ajax
     //1.创建ajax对象
     var oXhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
     //2.和服务器建立联系,告诉服务器你要取什么文件
     oXhr.open(defaults.method, defaults.url, defaults.async);
     //3.发送请求
     if(defaults.method === 'GET')    
         oXhr.send(null);
     else{
         oXhr.setRequestHeader("Content-type", defaults.contentType);
         oXhr.send(defaults.data);
     }    
     //4.等待服务器回应
     oXhr.onreadystatechange = function (){
         if(oXhr.readyState === 4){
             if(oXhr.status === 200)
                 defaults.success.call(oXhr, oXhr.responseText);
             else{
                 defaults.error();
             }
         }
     };
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值