【问题标题】:Bad charset submitted in jQuery Ajax form以 jQuery Ajax 表单提交的错误字符集
【发布时间】:2011-07-08 09:26:09
【问题描述】:

在我的索引 PHP 页面中,我定义了这个字符集:

header("Content-Type: text/html; charset=UTF-8");

在 HTML 中带有meta 标签:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

在此页面上,我使用 Ajax (jQuery) 提交了一个表单:

$('#action_button').click(function() {
        var azione = $('#form-post').attr('action');
        var datiform = $('#form-post').serialize();
        send = $.ajax({
            type: "POST",
            url: azione,
            data: datiform,
            dataType: "json",
            beforeSend: function(){
                 ...
            },
            success: function(msg){
                ...
            }
        });
        return false;
    });

在接收数据的页面我设置了header

header("Content-Type: text/html; charset=UTF-8");

我请求发布数据:

$nome = htmlentities(rtrim(ltrim(strip_tags(addslashes($_POST['nome']))))) ;

但是数据没有在数据库中正确注册;字符 òèìùàé 被错误地解释,例如 ÄÃ 和类似的。我测试了不同的方法,但没有成功,但如果我发送没有 Ajax (jQuery) 的表单,它工作正常!

【问题讨论】:

  • 你的文件是 UTF-8 字符集的吗?在某个编辑器中打开您的文件并检查它的字符集。
  • jQuery.ajax 文档指出“数据将始终使用 UTF-8 字符集传输到服务器;您必须在服务器端对其进行适当解码。”我不认为这是 jQuery 的问题
  • 我认为你的数据库排序有问题...

标签: php javascript jquery ajax character-encoding


【解决方案1】:

问题可能出在您的数据库中。您可以echo $nome; 确定。我建议您尝试使用此功能连接到数据库。还将您的表格字符集转换为utf8_unicode_ci...

function connect($server, $database, $username, $password, $charset = "UTF8"){
    $link = mysql_connect($server, $database, $password);
    if(!$link){
        die("Unable to connect to database server.");
    }
    mysql_selectdb($database);
    if(function_exists("mysql_set_charset")){
        mysql_set_charset($charset, $link);
    }else{
        mysql_query("SET NAMES $charset");   
    }
}

设置表格字符集...

ALTER TABLE `my_table` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci

数据库...

ALTER DATABASE `my_database` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2011-04-23
    相关资源
    最近更新 更多