Corrupted characters when jQuery.AJAX sends to PHP (UTF-8 & ISO-8859 incompatibilities)

一个人想着一个人 提交于 2019-12-24 14:24:01

问题


I have a javascript/PHP script that does the following:

Uses javascript to find text on a web-page.
Transmits the text using jQuery AJAX to a PHP page.
The PHP stores the text in a MySQL database. 

The trouble is, when I look at what has been stored in the database, some non-ASCII characters are corrupted.

I have simplified the problem and printed out the character codes of each letter to investigate what is going on.

For example: send over a single character, the pound sterling symbol. When I check in PHP, what is being received is characters 0xC2 followed by 0xA3 (capital A circumflex follwed by pound sterling). Ie getting a spurious extra character  before the £).

I've looked at similar problems which suggested setting the jQuery.ajax contentType etc, but none of this made sense to me.

Thanks


回答1:


Sounds like you're got mixed character sets. UTF-8, ISO-8859 there. PHP won't mangle the single pound character into two on its own, but the browser might if it's been told to expect iso-8859 but is sent UTF-8 instead. the  is a dead giveaway for that.

Basically, make sure you're using UTF-8 at all stages of processing (database, PHP, html) and usually things will work much better.




回答2:


Finally got this to work.

The problem seems to be that the jQuery.ajax transmits data to the server using UTF-8 but the PHP expects iso-8859-1.

Solution: in PHP convert UTF-8 to ISO using the utf8_decode function, e.g.

$incomming = utf8_decode($_REQUEST('incomming'));

And when you send data back for the ajax return handler, use utf8_encode() to convert back to UTF-8.

Other things that seem to work include using the javascript escape() function on the data prior to transmission to the server and then un-escape the data in PHP with URLdecode().

Other things I tried but couldn't get to work:

I tried to make ajax transmit in iso-8859-1 so it would be compatible with the PHP: In the jquery.ajax settings: contentType: "application/x-www-form-urlencoded; charset=iso-8859-1". Seemed to have no effect.

I tried to make PHP use UTF-8: header('Content-Type: text/html; charset=utf-8'). Again it didnt work.



来源:https://stackoverflow.com/questions/6616240/corrupted-characters-when-jquery-ajax-sends-to-php-utf-8-iso-8859-incompatibi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!