好程序员web前端教程分享前端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);
        }
    }
}