关于UTF-8的客户端用AJAX方式获取GB2312的服务器端乱码问题的解决办法_javascript技巧
程序员文章站
2022-03-26 10:04:20
...
客户端是UTF-8编码,这也是现在大家公认的标准编码
在这种情况下,实用AJAX异步获取GB2312编码的服务器端信息时,不可避免的要遇到汉字乱码问题
因为目标数据是GB2312,但XMLHttpRequest默认是用UTF-8来进行数据封装的,因此会产生乱码
相信很多人都在用轻量级的JS工具集-prototype.js,它的AJAX功能同样很出色
我也一直在用它,因此对于这个问题也一直是基于 prototype.js来考虑的
但经过多次试验,还是没能把它返回的 responseText 转成正确的编码格式
后来了解到,在XMLHttpRequest对象的 responseBody 属性中,保存了原始的数据信息
但prototype.js的AJAX功能返回的 responseBody 属性是 undefined,看来还是要自己动手了
经过近一个小时的敲打,一个短小精悍的AJAX框架腾空出世了,哈哈,不过功能还是很全的
里面某些写法借鉴了另一个轻量级的AJAX框架-bingo.js的实现方式
调用方式及注释:
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);
}
注意看其中的两个函数:
、URLEncoding :对参数进行编码
、bytes2BSTR :对返回的数据进行解码
这两个函数直接借鉴了网络上很流行的两个编码函数,不过都是用vbs写的
需要把这两个函数也附加到上面的页面里:
Function URLEncoding(vstrIn)
strReturn = ""
For i = 1 To Len(vstrIn)
ThisChr = Mid(vStrIn,i,1)
If Abs(Asc(ThisChr)) strReturn = strReturn & ThisChr
Else
innerCode = Asc(ThisChr)
If innerCode 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 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 源码:
/**
2 * myAjax
3 * by netwild
4 * netwild@163.com
5 */
6 var myAjaxConfig = {
7 "url":""
8 ,"params":""
9 ,"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;ntry {
_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);
}
在这种情况下,实用AJAX异步获取GB2312编码的服务器端信息时,不可避免的要遇到汉字乱码问题
因为目标数据是GB2312,但XMLHttpRequest默认是用UTF-8来进行数据封装的,因此会产生乱码
相信很多人都在用轻量级的JS工具集-prototype.js,它的AJAX功能同样很出色
我也一直在用它,因此对于这个问题也一直是基于 prototype.js来考虑的
但经过多次试验,还是没能把它返回的 responseText 转成正确的编码格式
后来了解到,在XMLHttpRequest对象的 responseBody 属性中,保存了原始的数据信息
但prototype.js的AJAX功能返回的 responseBody 属性是 undefined,看来还是要自己动手了
经过近一个小时的敲打,一个短小精悍的AJAX框架腾空出世了,哈哈,不过功能还是很全的
里面某些写法借鉴了另一个轻量级的AJAX框架-bingo.js的实现方式
调用方式及注释:
复制代码 代码如下:
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);
}
注意看其中的两个函数:
、URLEncoding :对参数进行编码
、bytes2BSTR :对返回的数据进行解码
这两个函数直接借鉴了网络上很流行的两个编码函数,不过都是用vbs写的
需要把这两个函数也附加到上面的页面里:
复制代码 代码如下:
Function URLEncoding(vstrIn)
strReturn = ""
For i = 1 To Len(vstrIn)
ThisChr = Mid(vStrIn,i,1)
If Abs(Asc(ThisChr)) strReturn = strReturn & ThisChr
Else
innerCode = Asc(ThisChr)
If innerCode 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 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 源码:
复制代码 代码如下:
/**
2 * myAjax
3 * by netwild
4 * netwild@163.com
5 */
6 var myAjaxConfig = {
7 "url":""
8 ,"params":""
9 ,"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
_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);
}
上一篇: 详解php fwrite() 函数写入文件实例详解
下一篇: 如何使用源生css3实现圆环加载进度条