天天看點

釋出我的Ajax工具類(myAjax)。可解決UTF-8用戶端擷取GB2312的伺服器端出現的亂碼問題

大多數的用戶端都采用UTF-8編碼,這也是現在實作國際化最常用的編碼格式

在這種情況下,實用AJAX異步擷取GB2312編碼的伺服器端資訊時,不可避免的要遇到漢字亂碼問題

因為目标資料是GB2312,但XMLHttpRequest預設是用UTF-8來進行資料封裝的,是以會産生亂碼

相信很多人都在用輕量級的JS工具集-prototype.js,它的AJAX功能同樣很出色

我也一直在用它,是以對于這個問題也一直是基于 prototype.js來考慮的

但經過多次試驗,還是沒能把它傳回的 responseText 轉成正确的編碼格式

後來了解到,在XMLHttpRequest對象的 responseBody 屬性中,儲存了原始的資料資訊

但prototype.js的AJAX功能傳回的 responseBody 屬性是 undefined,看來還是要自己動手了

經過近一個小時的敲打,一個短小精悍的AJAX架構騰空出世了,哈哈,不過功能還是很全的

調用方式及注釋:

myAjaxCall({      
    url : 'xxxxx.jsp' //目标頁面位址      
    ,params : URLEncoding('prm1=參數1&prm2=參數2') //參數串資訊      
    ,method : 'POST' //發送方式POST or GET      
    ,callBack : retValue //回調函數名稱      
    ,isBody : true //是否傳回 responseBody ,預設傳回 responseText      
    //,isXml : false //是否以XML格式傳回資料      
    //,errorReport : false //發送錯誤時,是否彈出提示      
    //,attachs : {} //附加的其他參數,可傳遞給回調函數      
});      
function retValue(res,att){      
    var strRet = bytes2BSTR(res);      
    alert(strRet);      
}      

注意看其中的兩個函數:

1、URLEncoding :對參數進行編碼

2、bytes2BSTR :對傳回的資料進行解碼

這兩個函數直接借鑒了網絡上很流行的兩個編碼函數,不過都是用vbs寫的

需要把這兩個函數也附加到上面的頁面裡:

Function URLEncoding(vstrIn)   
    strReturn = ""   
    For i = 1 To Len(vstrIn)   
        ThisChr = Mid(vStrIn,i,1)   
        If Abs(Asc(ThisChr)) < &HFF Then   
            strReturn = strReturn & ThisChr   
        Else   
            innerCode = Asc(ThisChr)   
            If innerCode < 0 Then   
                innerCode = innerCode + &H10000   
            End If   
            Hight8 = (innerCode  And &HFF00) \ &HFF   
            Low8 = innerCode And &HFF   
            strReturn = strReturn & "%" & Hex(Hight8) &  "%" & Hex(Low8)   
     End If   
    Next   
    URLEncoding = strReturn   
End Function   
Function bytes2BSTR(vIn)   
    strReturn = ""   
    For i = 1 To LenB(vIn)   
        ThisCharCode = AscB(MidB(vIn,i,1))   
        If ThisCharCode < &H80 Then   
            strReturn = strReturn & Chr(ThisCharCode)   
        Else   
            NextCharCode = AscB(MidB(vIn,i+1,1))   
            strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))   
            i = i + 1   
        End If   
    Next   
    bytes2BSTR = strReturn   
End Function      

下面附上我寫的輕量級Ajax架構 - myAjax.js 源碼:

/**
 * Ajax工具類: myAjax
 * @author     網無忌(netwild)
 * @email      [email protected]
 * @qq         52100641
 * @version    1.0
 */
var myAjaxConfig = {   
    "url":""   
    ,"params":""   
    ,"method":"GET"   
    ,"callBack":function(){}   
    ,"isXml":false   
    ,"isBody":false   
    ,"isCache":false   
    ,"errorReport":true   
    ,"statePoll":null   
    ,"postData":null   
    ,"attachs":{}   
};   
function myAjaxCall(requestJson){   
    var attach;   
    if(requestJson && typeof requestJson == "object"){   
        if(requestJson.url){myAjaxConfig.url = requestJson.url;}   
        if(requestJson.params){myAjaxConfig.params = requestJson.params;}   
        if(requestJson.method){myAjaxConfig.method = requestJson.method;}   
        if(requestJson.callBack){myAjaxConfig.callBack = requestJson.callBack;}   
        if(requestJson.isXml){myAjaxConfig.isXml = requestJson.isXml;}   
        if(requestJson.isBody){myAjaxConfig.isBody = requestJson.isBody;}   
        if(requestJson.isCache){myAjaxConfig.isCache = requestJson.isCache;}   
        if(requestJson.statePoll){myAjaxConfig.statePoll = requestJson.statePoll;}   
        if(requestJson.attachs){myAjaxConfig.attachs = requestJson.attachs;}   
    }   
    if(!myAjaxConfig.isCache){   
        var nocache = new Date().getTime();   
        if(myAjaxConfig.url.indexOf("?")>0){myAjaxConfig.url += "&nocache=" + nocache;}   
        else{myAjaxConfig.url += "?nocache=" + nocache;}   
    }   
    var newCall = new myAjaxCore();   
    newCall.init();   
}   
function myAjaxCore(){   
    var _self = this;   
    var _state,_status;   
    var _httpRequest,_attach;   
    ////////////////////////////////////////////////////   
    this.init = function(){   
        if (window.XMLHttpRequest){   
            _httpRequest = new XMLHttpRequest();   
            if (_httpRequest.overrideMimeType) _httpRequest.overrideMimeType('text/xml'); 
        }else if (window.ActiveXObject) {   
            var MSXML = ['MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];   
            for(var n=0;n<MSXML.length;n++){    
                try {    
                    _httpRequest = new ActiveXObject(MSXML[n]);    
                    break;    
                }catch(e){}   
            }    
        }   
        with(_httpRequest) {   
            onreadystatechange = _self.getResponse;   
            open(myAjaxConfig.method,myAjaxConfig.url,true);   
            if(myAjaxConfig.method == "POST" && (myAjaxConfig.params != "")){   
                setRequestHeader("Content-Length",myAjaxConfig.params.length);      
                setRequestHeader("Content-Type","application/x-www-form-urlencoded");   
                send(myAjaxConfig.params);   
            }else{   
                var textType = myAjaxConfig.isXml?"text/xml":"text/plain";   
                _httpRequest.setRequestHeader('Content-Type',textType);   
                if(browser.IE) setRequestHeader("Accept-Encoding", "gzip, deflate");   
                else if(browser.FF) setRequestHeader("Connection","close");   
                send(null);   
            }   
        }   
    };   
    ////////////////////////////////////////////////////   
    this.getResponse = function(){   
        _state = _httpRequest.readyState;   
        if(_httpRequest.readyState == 4 && _httpRequest.status){_status = _httpRequest.status;}   
        if(myAjaxConfig.statePoll){myAjaxConfig.statePoll(_httpRequest.readyState);}   
        if(_httpRequest.readyState==4 && _httpRequest.status>=400){   
            _self.abort();   
            _self.alertf("ERROR:HTTP response code "+_httpRequest.status);   
        }   
        if(_httpRequest.readyState==4 && _httpRequest.status==200){   
            var response_content;   
            if(myAjaxConfig.isXML){   
                response_content = _httpRequest.responseXML;   
            }else if(myAjaxConfig.isBody){   
                response_content = _httpRequest.responseBody;      
            }else{   
                response_content = _httpRequest.responseText;   
            }          
            if(typeof myAjaxConfig.callBack == "function"){   
                myAjaxConfig.callBack(response_content,myAjaxConfig.attachs);   
            }else{   
                eval(myAjaxConfig.callBack+"(response_content,myAjaxConfig.attachs)");   
            }   
        }   
    };   
    ////////////////////////////////////////////////////   
    this.abort=function(){_httpRequest.abort();};   
    this.state=function(){return _state;};   
    this.status=function(){return _status;};   
    this.destory=function(){_self.abort();delete(_httpRequest);};   
    this.alertf=function(error){if(myAjaxConfig.errorReport){alert(error);}};   
}   
if(!browser){   
    var browser={};   
    browser.IE = browser.ie = window.navigator.userAgent.indexOf("MSIE")>0;   
    browser.Firefox = browser.firefox = browser.FF = browser.MF = navigator.userAgent.indexOf("Firefox")>0;   
    browser.Gecko = browser.gecko = navigator.userAgent.indexOf("Gecko")>0;   
    browser.Safari = browser.safari=navigator.userAgent.indexOf("Safari")>0;   
    browser.Camino = browser.camino=navigator.userAgent.indexOf("Camino")>0;   
    browser.Opera = browser.opera=navigator.userAgent.indexOf("Opera")>0;   
    browser.other = browser.OT=!(browser.IE || browser.FF || browser.Safari || browser.Camino || browser.Opera);   
}      

寵辱不驚,看庭前花開花落;去留無意,望天上雲卷雲舒

繼續閱讀