发送数据的编码无效

时间:2012-05-28 16:47:25

标签: php jquery ajax encoding

我有一个小聊天盒,一切正常,除了发送特殊的拉丁字符,如äöü。

这是发送输入的帖子,按下很快输入(它被放置在正文中,而不是在标题中,无法弄清楚如何将其放入标题中 - &gt; vBulletin模板):< / p>

<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;

insertShout logic

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作为charset,但没有运气。此外,帖子没有帮助。使用这种ajax来拉取聊天框内容的工作方式就像一个魅力(直接插入带有phpmyadmin的db的特殊字符显示正确)。

问题不在于将字符插入数据库。当我在第一个入口点转储$ _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

1 个答案:

答案 0 :(得分:3)

替换

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()