Causes of AJAX garbled characters
Because XMLHTTP uses Unicode encoding to upload data, and generally uses gb2312 as the page, garbled characters are generated when the page is displayed. When the page is obtained, XMLHttp returns UTF-8 encoding, which causes garbled characters in the display.
One solution is to display the declaration as GB2312 in the PHP file.
Header ("Content-Type: text/html; charset = GB2312 ");
Transcode the Chinese characters sent to the server.
As follows:
$ _ POST ["content"] = iconv ("UTF-8", "gb2312", $ _ POST ["content"]);
This can solve the garbled problem.
Method 2, is using UTF-8 encoding. I will not talk about it here.
Attached test routine
Client
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Title> ajax post test </title>
</Head>
<Body>
<Div id = "msg"> </div>
<Script language = "javascript">
/**
* Initialize an xmlhttp object
*/
Function InitAjax ()
{
Var ajax = false;
Try {
Ajax = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
Ajax = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (E ){
Ajax = false;
}
}
If (! Ajax & typeof XMLHttpRequest! = 'Undefined '){
Ajax = new XMLHttpRequest ();
}
Return ajax;
}
// There is a form and a display layer on the form test page.
Function sendData ()
{
Var msg = document. getElementById ("msg ");
Var f = document. form1;
Var c = f. content. value;
// The URL for receiving data
Var url = "dispmsg. php ";
Var poststr = "content =" + c;
Var ajax = InitAjax ();
Ajax. open ("POST", url, true );
Ajax. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
Ajax. send (poststr );
Ajax. onreadystatechange = function (){
If (ajax. readyState = 4 & ajax. status = 200 ){
Alert ("I got something ");
Msg. innerHTML = ajax. responseText;
}
}
}
</Script>
<Form name = 'form1'>
<Input type = "text" name = 'content' size = 10>
<Input type = "button" value = "OK" onclick = "sendData ()"> <! -- An error occurred when I used the submit -->
</Form>
</Body>
</Html>
Server
<? Php
Header ("Content-Type: text/html; charset = GB2312 ");
If ($ _ POST ['content'])
{
$ _ POST ["content"] = iconv ("UTF-8", "gb2312", $ _ POST ["content"]);
Print ("content is". $ _ POST ['content']);
}
Else
{
Print ("NO content to send ");
}
?>
Reference from: http://www.blogjava.net/huyi2006/articles/86154.html