Solve Ajax to get the page directly display garbled method

Source: Internet
Author: User
Tags string

As we all know, XMLHTTP in the communication is the UTF code, and a lot of information in the domestic Web page is the use of GBK encoding, so when directly through Ajax to connect the Web page, and will get the information directly displayed will appear garbled phenomenon, sometimes can not change the server side of the page code ( For example, to get other Web site weather information, at this time only in the client through JS to do the work of coding.

The following JS is used to convert the GBK encoded string returned by the server side to a UTF encoded string:


function Gb2utf8 (data) {
var glbencode = [];
Gb2utf8_data = data;
Execscript ("Gb2utf8_data = MidB (gb2utf8_data, 1)", "VBScript");
var t=escape (gb2utf8_data). Replace (/%u/g, ""). Replace (/(. { 2}) (. { 2})/g, "%$2%$1"). Replace (/% [A-z].)% (. {2}) /g, "@$1$2");
T=t.split ("@");
var i=0,j=t.length,k;
while (++I<J) {
K=t[i].substring (0,4);
if (!glbencode[k]) {
Gb2utf8_char = eval ("0x" +k);
Execscript ("Gb2utf8_char = Chr (Gb2utf8_char)", "VBScript");
Glbencode[k]=escape (Gb2utf8_char). substring (1,6);
}
T[i]=glbencode[k]+t[i].substring (4);
}
Gb2utf8_data = Gb2utf8_char = null;
Return unescape (T.join ("%")); }


With this code, you can encode the returned page content directly:
var Response=gb2utf8 (response.responsebody);


After such a transfer code to obtain the content of the page will not have garbled phenomenon;
Of course, if the server-side page uses a utf-8 encoding , there is no need for coding at all.



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.