doujiang5211 2011-07-07 19:48
浏览 35
已采纳

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

  • 写回答

2条回答 默认 最新

  • douna2014 2011-07-08 17:32
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度