How to correctly handle PHPAjax 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 retrieving the page, XMLHttp returns UTF-8 encoding.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 of the solutions to PHP Ajax garbled code 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 PHP Ajax garbled problem.
Method 2, is using UTF-8 encoding. I will not talk about it here.
PHP Ajax garbled solution example 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
- </Head>
- <Body>
- <P id = "msg"> </p>
- <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 XMLHttp
Request! = '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>
- Onclick = "sendData ()"> <! -- An error occurred when I used the submit -->
- </Form>
- </Body>
- </Html>
PHP Ajax garbled solution example on the server side
- <? 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 ");
- }
- ?>
The above code example is a solution to PHP Ajax garbled code. I hope it will be helpful to other users who need it.
Bytes. When retrieving the page, XMLHttp returns UTF-8 encoding...