ajax的封装通俗易懂

function obj2Ognl(data){
        var res = [];
        data.t = new Date().getTime();//get请求url只会返回出第一次数据故得加一个随机数
        for(var key in data){
            //encodeURIComponent()将汉字转化为一堆数字百分号
        	res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));//[userName = du,userPad = 111]
        }
        return res.join("&");//join方法会将数组转化为字符串,userName = du&userPad = 111
	}
//方法2
// function obj2Ognl(data){
//      var str = '';
//      var mark = true;
//      for(var key in data){
//         str+=mark ? '' : "&";
//         str+=key+"="+data[key]; 
//         mark = false;
//      }
//      return str;
// }

function ognl2Obj(){
    var result = {};
    var ognl = decodeURI(location.search).substring(1).split('&');//一个数组['name="黎明"','id=13']
    for(var index in ognl){              //此时是遍历数组
        var str = ognl[index].split('=');//一个数组['name','黎明']
        result[str[0]] = str[1];
    }
    return result;
}
function ajax(opation){
	var str = objto(opation.data);
	var xhr,timer;
	//1.兼容IE创建一个异部对象
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest();
	}else{
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	}
    //类型判断是post还是get
    if(opation.type.toLowerCase()==='get'){//你传入的是大写会将其转换为小写,你传入是小写刚刚好
        xhr.open(opation.type,opation.url+"?"+str,true);
        xhr.send(); 
    }else{
        xhr.open(opation.type,opation.url,true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send(str);
    }
    //4.监听状态变化
    xhr.onreadystatechange=function(ev){
    	//请求初始化
        if(xhr.readyState===4){
        	//判读请求是否成功
        	if(xhr.status>=200&&xhr.status<300||xhr.status===304){
                 opation.success(xhr);
        	}else{
                opation.erro(xhr);
        	}
        }
    }
    //判断外界是否传入一个超时时间
    if(opation.timeout){
    	timer = setInterval(function(){
             xhr.abort();//timeout时间之后请求终断并清除定时器
             clearInterval(timer);
    	},opation.timeout);
    }
}

猜你喜欢

转载自blog.csdn.net/du111_/article/details/83345701