使用原生js寫ajax

 

 

// 使用原生js 封裝ajax
// 兼容xhr對象
function createXHR(){
    if(typeof XMLHttpRequest != "undefined"){ // 非IE6瀏覽器
        return new XMLHttpRequest();
    }else if(typeof ActiveXObject != "undefined"){   // IE6瀏覽器
        var version = [
                    "MSXML2.XMLHttp.6.0",
                    "MSXML2.XMLHttp.3.0",
                    "MSXML2.XMLHttp",
        ];
        for(var i = 0; i < version.length; i++){
            try{
                return new ActiveXObject(version[i]);
            }catch(e){
                //跳過
            }
        }
    }else{
        throw new Error("您的系統或瀏覽器不支持XHR對象!");
    }
}
// 轉義字符
function params(data){
    var arr = [];
    for(var i in data){
        arr.push(encodeURIComponent(i) + "=" + encodeURIComponent(data[i]));
    }
    return arr.join("&");
}
// 封裝ajax
function ga_ajax(obj){
    var xhr = createXHR();
    obj.url = obj.url + "?rand=" + Math.random(); // 清除緩存
    obj.data = params(obj.data);      // 轉義字符串
    if(obj.method === "get"){      // 判斷使用的是不是get方式發送
        obj.url += obj.url.indexOf("?") == "-1" ? "?" + obj.data : "&" + obj.data;
    }
    // 異步
    if(obj.async === true){
        // 異步的時候須要觸發onreadystatechange事件
        xhr.onreadystatechange = function(){
            // 執行完成
            if(xhr.readyState == 4){
                callBack();
            }
        }
    }
    xhr.open(obj.method,obj.url,obj.async);  // false是同步 true是異步 // "demo.php?rand="+Math.random()+"&name=ga&ga",
    if(obj.method === "post"){
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send(obj.data);
    }else{
        xhr.send(null);
    }
    // xhr.abort(); // 取消異步請求
    // 同步
    if(obj.async === false){
        callBack();
    }
    // 返回數據
    function callBack(){
        // 判斷是否返回正確
        if(xhr.status == 200){
            obj.success(xhr.responseText);
        }else{
            obj.Error("獲取數據失敗,錯誤代號爲:"+xhr.status+"錯誤信息爲:"+xhr.statusText);
        }
    }
}

var html = document.getElementsByTagName("html")[0];
html.onclick = function(){
    ga_ajax({
        "method" : "post",
        "url" : "demo.php",
        "data" : {
            "name" : "gao",
            "age" : 100,
            "num" : "12346&598"
        },
        "success" : function(data){
            alert(data);
        },
        "Error" : function(text){
            alert(text);
        },
        "async" : false
    });
}
相關文章
相關標籤/搜索