Solution to the Problem of garbled code on the server side of the UTF-8 client using AJAX Method

Source: Internet
Author: User

The client is the UTF-8 code, which is now recognized as the standard code
In this case, when AJAX is used to asynchronously obtain the server information of GB2312 encoding, Chinese Character garbled characters are inevitable.
Because the target data is GB2312, but XMLHttpRequest is encapsulated by UTF-8 by default, it will produce garbled
I believe many people are using the lightweight JS tool set prototype. js. Its AJAX function is equally outstanding.
I have been using it, so I have been considering this issue based on prototype. js.
However, after many experiments, it still failed to convert responseText returned by it into the correct encoding format.
Later I learned that the original data information is saved in the responseBody attribute of the XMLHttpRequest object.
However, the responseBody attribute returned by the AJAX function of prototype. js is undefined. It seems that you have to do it yourself.
After nearly an hour of hitting, a short and sophisticated AJAX framework was born.
Some of the writing methods refer to the implementation method of bingo. js, another lightweight AJAX framework.
Call method and comment: Copy codeThe Code is as follows: myAjaxCall ({
Url: 'xxxxx. jsp '// target page address
, Params: URLEncoding ('prm1 = parameter 1 & prm2 = parameter 2') // parameter string Information
, Method: 'post' // sending method POST or GET
, CallBack: retValue // callBack function name
, IsBody: true // whether to return responseBody. responseText is returned by default.
//, IsXml: false // whether to return data in XML format
//, ErrorReport: false // whether to display a prompt when an error is sent
//, Attachs :{}// additional parameters can be passed to the callback function
});
Function retValue (res, att ){
Var strRet = bytes2BSTR (res );
Alert (strRet );
}

Pay attention to the two functions:

, URLEncoding: encode the Parameter
, Bytes2BSTR: decodes the returned data

These two functions use two popular coding functions on the network, but they are all written in vbs.
You need to add these two functions to the above page:Copy codeThe Code is as follows: 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

The lightweight Ajax framework I wrote-myAjax. js source code is attached below:Copy codeThe Code is as follows :/**
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 <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 );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.