基於JavaScript封裝的Ajax工具類

前段是件因爲工做須要無奈編寫了一個給予JavaScript封裝的工具類,技術有限,誤噴,感謝你們的支持。json

一、如下是JavaScript 的 Ajax 工具類。瀏覽器

function createXMLHttpRequest(){
    var req;
    if(window.XMLHttpRequest){
        //兼容非IE  而且兼容 IE7以上的瀏覽器
        req = new XMLHttpRequest();
    }else if(window.ActiveXObject){
        //在 Internet Explorer 5.5 及其後版本中可用
        try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            //在 Internet Explorer 6 中可用
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }
    }
    
    return req;
}

/*
參數介紹:
method:提交方式(get,post)
url:請求的路徑
param:須要傳遞的參數
async:是否一步
type:返回值類型(xml,json,默認字符串)
fn200:是一個function 處理請求成功後的的事情
fn404:是一個function 處理請求失敗報404錯誤
fn500:是一個function 處理請求失敗報500錯誤
*/
function sendAjaxReq(method,url,param,async,type,fn200,fn404,fn500,loading){
    var req = createXMLHttpRequest();
    //2.定義處理響應
    req.onreadystatechange = function (){
        if(req.readyState == 4){
            if(req.status == 200){
                if(fn200){
                    var result;
                    if(null != type && 'xml' == type.toLowerCase()){
                        result = req.responseXML;
                    }else if(null != type && 'json' == type.toLowerCase()){
                        jsonStr = req.responseText;
                        if(document.all){
                            result = eval('(' + jsonStr + ')');
                        }else{
                            result = JSON.parse(jsonStr);
                        }
                    }else{
                        result = req.responseText;
                    }
                    fn200(result);
                    
                }
            }else if(req.status == 404){
                if(fn404){
                    fn404(); 
                }
            }else if(req.status == 500){
                if(fn500){
                    fn500();
                }
            }
        }else{
            if(loading){
                loading();
            }
        }
    };
    if('get' == method.toLowerCase()){
        req.open(method, url + (param == null ? '' : '?'+param), async);
        req.send(null);
    }else if('post' == method.toLowerCase()){
        //1.定義發送請求  請求的方式   請求的地址    是否異步;
        req.open(method, url, async);
        req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        req.send(param);
    }
  
}

 

2.調用方式:app

function test(){
     var url = "test?date=" + new Date();
     sendAjaxReq("get",url,null,true,'json',function(result){
         //此處是請求成功後回調方法,可作請求成功後的處理,result是後臺返回的參數
     },function (){
     //此處能夠跳轉一個404頁面
   },function (){
     //此處是處理500錯誤
   },function (){
     //處理其餘問題
   });
}
相關文章
相關標籤/搜索