已发送数据的编码不起作用


Encoding of sent data not working

我有一个小聊天框,一切都在工作,除了发送像äöü这样的特殊拉丁字符。

这是发送输入的帖子,只要按下 enter(它放在正文中,而不是标题中,无法弄清楚如何将其放在标题中 --> vBulletin 模板):

<script type="text/javascript">
  $("#shout").keypress(function(e) {
    if(e.keyCode == 13) {
      $.ajax({
        url: "http://example.com/api.php",
        contentType: "text/html; charset=ISO-8859-1",
        data: {
          action: "shout",
          // This is what I found on the internet to
          // encode the data, but didn't help.
          message: $('<div />').text($("#shout").val()).html()
        },
        success: function() {
          $("#shout").val("");
        }
      })
    }
  });
</script>

在服务器端

// Insert shout
case "shout":
if(isset($_GET['message']) && $_GET['message'] != "") {
  $mc->insertShout($userid, mktime(), $_GET['message']);
}
break;

插入喊音逻辑

public function insertShout($userid, $date, $message, $notification = 0) {
  $sql = "INSERT INTO
  vb_chatbox_shout (userid, dateline, message, message_raw, notification)
        VALUES
          (?, ?, ?, ?, ?)";
  $stmt = $this->db->prepare($sql);
  $stmt->bindParam(1, $userid);
  $stmt->bindParam(2, $date);
  $stmt->bindParam(3, $message);
  $stmt->bindParam(4, $message);
  $stmt->bindParam(5, $notification);
  if(!$stmt->execute()) {
    var_dump($stmt->errorInfo());
  }
  return 1;
}

我尝试使用 utf-8 作为字符集,但没有运气。另外,帖子没有帮助。使用这种 ajax 来拉取聊天框内容就像一个魅力(使用 phpmyadmin 直接插入数据库的特殊字符正确显示)。

问题不在于将字符插入数据库。当我在第一个入口点转储 $_GET var 时,它已经搞砸了,所以问题出在 jQuery 和 PHP 之间。

新标头

GET /api.php?action=shout&message=%25C3%25B6%25C3%25A4%25C3%25BC HTTP/1.1
Host: example.com
Connection: keep-alive
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5
Accept: */*
Referer: http://example.com/forum/forum.php
Accept-Encoding: gzip,deflate,sdch
Accept-Language: de
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: skimlinks_enabled=1; bb_lastvisit=1316066700; bb_lastactivity=0; bb_userid=1;

HTTP/1.1 200 OK
Date: Mon, 28 May 2012 17:26:14 GMT
Server: Apache
X-Powered-By: PHP/5.2.9
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8

替换

message: $('<div />').text($("#shout").val()).html()

message: encodeURIComponent($('<div />').text($("#shout").val()).html())

在 JavaScript 中,然后替换

$mc->insertShout($userid, mktime(), $_GET['message']);

$mc->insertShout($userid, mktime(), urldecode($_GET['message']));

并添加

header('Content-type: text/html; charset=utf-8');

在 PHP 文件的开头。

如果 PHP urldecode不起作用,请尝试将其替换为 rawurldecode()