前端javascript练习题Ajax封装

前端javascript练习题Ajax封装
ajax的根柢封装 ----有必要把握
function ajax(url,fn){

if(window.XMLHttpRequest){
var xhr = new XMLHttpRequest();
}else{
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("get",url,true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var data = xhr.responseText;
fn(data);
}
}
}}

ajax的无缺封装
function ajax(obj){

//obj -> type url data success
var str = "";
for(var key in obj.data){
str += key+"="+obj.data[key]+"&";
}
//str = str.substring(0,str.length-1);
str = str.replace(/&$/,"");
if(window.XMLHttpRequest){
var xhr = new XMLHttpRequest();
}else{
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if(obj.type.toUpperCase()=="GET"){
if(obj.data){
var url = obj.url + "?" + str;
}else{
var url = obj.url;
}
xhr.open("get",url,true);
xhr.send();
}
if(obj.type.toUpperCase()=="POST"){
xhr.open("post",obj.url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(str);
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var data = xhr.responseText;
obj.success(data);
}
}
}