ajax,php,mysql和charset的问题

时间:2012-12-16 11:04:59

标签: php mysql ajax character-encoding xmlhttprequest

我使用POST方法将一些值传递给带有ajax的php文件。

当php文件收到像àè这样的特殊字符时,它正确地看到了它,但当我把它放入查询时,它们会在数据库中保存不良内容。

我哪里错了?我试图将charset更改为mysql表...但没有。

这是我的代码。

Ajax文件:

if (window.XMLHttpRequest)
            {
                xmlhttp=new XMLHttpRequest();
            }
            else
            {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }   
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    var response = xmlhttp.responseText;
                    if(response == "error")
                    {
                        post_status.innerHTML = "<font color=\"red\">Si è verificato un errore</font>";
                    }
                    else if(response == "error_tofast")
                    {
                        post_status.innerHTML = "<font color=\"red\">Hai postato un commento meno di un minuto fa, attendi</font>";
                    }
                    else if(response == "posted")
                    {
                        post_status.innerHTML = "<font color=\"green\">Post aggiunto con successo</font>";
                        document.getElementById("newcommenttxt").value = "";
                        document.getElementById("newcommenttxt").rows = 2;
                        document.getElementById("list-comments").innerHTML = '<br><br><br><center><img style="cursor: progress;" width="60px" height="60px" src="./styles/images/loading.gif"></center>';
                        setTimeout("loadGagi()", 1000);
                        document.getElementById("reply_to_title").innerHTML = "";
                        replyto = -1;
                    }
                }
            }
            //xmlhttp.open("GET","./includes/postgagi?userid="+userid+"&replyto="+replyto+"&txt="+edited_comment,true);
            xmlhttp.open("POST","./includes/postgagi",true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
            xmlhttp.send("userid="+userid+"&replyto="+replyto+"&txt="+edited_comment+"");

1 个答案:

答案 0 :(得分:0)

在进行任何查询之前设置连接编码:

mysql_set_charset("utf8");
// or $mysqli->set_charset( "utf8" ); if you are using mysqli