当jQuery.AJAX发送到PHP乱码(UTF-8和; ISO-8859不兼容)发送到、乱码、不兼容、AJAX

2023-09-11 01:34:48 作者:莪的男人,伱別想別念別碰

我有做以下一个JavaScript / PHP脚本:

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. 

麻烦的是,当我在看什么被存储在数据库中,一些非ASCII字符已损坏。

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

我已经简化了这个问题,并打印每个字母出来的字符codeS调查正在发生的事情。

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

例如:通过发送一个字符时,英镑的象征。 当我检查在PHP中,正在接收的是为0xC2其次是0xA3执行字符 (资本抑扬由英镑follwed)。 即获得£前一个虚假的额外字符)。

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 £).

我看过类似的问题而提出设置jQuery.ajax的contentType等,但这些都不是有道理的我。

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

感谢

推荐答案

终于得到了这个工作。

这个问题似乎是该jQuery.ajax使用将数据发送到服务器UTF-8,但PHP预计ISO-8859-1。

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

解决方案:在PHP中使用utf8_de code函数转换为UTF-8至ISO,例如:

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

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

而当你将数据发送回阿贾克斯返回处理,使用utf8_en code()转换回UTF-8。

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

这似乎工作的其他东西包括使用事先传输到服务器,然后取消逃脱在PHP中的数据与URLde code(数据)。

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:

我试图让阿贾克斯发射的ISO-8859-1所以这将是与PHP兼容:在jquery.ajax设置:contentType中:应用程序/ x-WWW的形式urlen codeD;字符集= ISO-8859-1。 似乎没有任何效果。

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.

我试图让PHP使用UTF-8:标题(内容类型:text / html的;字符集= UTF-8)。 这又没有工作。

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