Home > Article > Backend Development > Solution to the problem of garbled Chinese characters in php ajax interaction_PHP tutorial
ajax only supports utf-8 format and cannot support gb2312 encoding format, so we often encounter garbled characters when using gb2312 encoding programs using ajax. I just found a solution: The data transmitted by the server is still encoded in gb2312, and the client uses js to convert Chinese characters into utf8 encoding and display it on the page.
ajax only supports utf-8 format and cannot support gb2312 encoding format, so we often encounter garbled characters when using gb2312 encoded programs using ajax. I just found a solution:
The data transmitted by the server is still gb2312 encoded, and the client uses js to convert Chinese characters into utf8 encoding and display it on the page
Method 1 json
1. The server-side json data is converted using the iconv function of the PHP tutorial: iconv('gb2312', 'utf8', "Converted string, output to the browser");
The client obtains utf8 data and then converts it to gb2312:
function gb2utf8(data){//gb encoding is, ie converts to Chinese through binary code utf8->gbk
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
k=t.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=glbencode[k]+t.substring(4);
}
gb2utf8_data = gb2utf8_char = null;
Return unescape(t.join("%"));
}
Second, header("content-type", "application/x-www-form-urlencoded; charset=gbk"); //Output header, set to gbk encoding
Third, call the above method before requesting data through ajax to specify the character set used in the request: xmlhttp.setrequestheader( "content-type", "application/x-www-form-urlencoded;charset=gbk");
Option 2
search.php
header("content-type: text/html; charset=gb2312");
include './search.htm';
?>
search.htm
Advanced Search
Advanced Search
ajax.php
header("content-type: text/html; charset=gb2312");
$schooltype = !empty($_post['schooltype']) ? $_post['schooltype'] : 0;
switch($schooltype) {
case 0:
echo "[['40', 'Taipingxi Town Hualibao Complete Primary School'],['41', 'Taipingxi Town Changling Heilongjiang Hope Primary School'],['42', 'Letianxi Town Junior High School'], ['43', 'Letianxi Town Liantuo Junior High School']]";
break;
Case 1:
echo "[['40', 'Taipingxi Town Hualibao Complete Primary School'],['41', 'Taipingxi Town Changling Heilongjiang Hope Primary School']]";
break;
Case 2:
echo "[['42', 'Lotte Creek Town Junior High School'],['43', 'Lotte Creek Town Liantuo Junior High School']]";
break;
Default:
break;
}
?>