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

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值