1. 程式人生 > >AJAX -- 原生 與 封裝 小記

AJAX -- 原生 與 封裝 小記

//1.建立xhr物件
var xhr;
if(window.XMLHttpRequest){
    xhr = XMLHttpRequest();
}else{
    xhr = new ActiveXObject("Microsoft.XMLHTTP");  //低版本 ie5-6 相容處理
}

//2.註冊回撥函式--事件處理程式
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
        ...  //相干什麼就幹什麼吧
    }
}

            //readyState: 0-未初始化
                          1-讀取中
                          2-已讀取
                          3-互動中
                          4-完成
//3.向伺服器發起連線:引數:請求方法,請求地址
xhr.open("get","/checkuser.do?username="+username);  //get
xhr.open("post","/checkuser.do");  //post
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");   //post請求頭

//4.傳參
xhr.send(null);    //get  地址傳參了,這裡不需要傳
xhr.send("usernae="+username)    //post

自己嘗試著玩封裝了一個ajax(呼叫傳參method,url,params,callback,async就行了):

var xhr;
if(window.XMLHttpRequest){
    xhr = XMLHttpRequest();
}else{
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

function myAjax(method,url,params,callback,async){
    if(async == undefined){
        async = true;            
    }
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            callback();
        }
    }
}

if(method == "get"){
    xhr.open(method,url+"?"+params,async);
}else if(method == "post"){
    xhr.open(method ,url,async);  //post
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");   
    xhr.send(params);
}


//async:true--非同步--預設方法--多執行緒同時做
     :false--同步--單執行緒一件一件來
因為window.onload不支援非同步,所以在window.onload中發起ajax的話要設定成同步

然後jq也有自己的ajax封裝方法:

$.ajax({
    type:"",   //get,post
    url:"",    //......do
    data:$("#id").serialize,    //表單序列化,多個引數可以寫成物件
    success:function(data){
        //執行成功回撥函式 函式體
    },
    async:true
})