Home  >  Article  >  Backend Development  >  jquery ajax交付中文出现乱码

jquery ajax交付中文出现乱码

WBOY
WBOYOriginal
2016-06-13 10:35:01785browse

jquery ajax提交中文出现乱码?
提交页面为submit.htm代码如下

HTML code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><meta content="text/html; charset=utf-8" http-equiv="Content-Type"><title>欢迎</title><meta http-equiv="X-UA-Compatible" content="IE=edge">...            $.ajax({              type:"POST",              url: "xx/add_post.php",              data:'aa='+escape($('#aa').val())+'&bb='+$('#bb').val(),              success: function(html){ alert('添加成功!'); }            });     ....

接收数据页为add_post.php
PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php header("Content-Type:text/html;charset=utf-8");                     date_default_timezone_set("PRC");                     try{                        $pdo=new PDO("mysql:host=localhost;dbname=acom", "root", "abcdefghi");    }catch(PDOException $e){                        echo $e->getMessage();    }    $stmt=$pdo->prepare("insert into acom_a(aa, bb) values(:aa, :bb)");          $stmt->execute(array(":aa"=>$_POST["aa"], ":bb"=>$_POST["bb"]));?>


aa字段存入中文为乱码,bb是英文正常!

------解决方案--------------------
单独执行 add_post.php 文件插入中文乱码吗?
------解决方案--------------------
encodeURI($('#bb').val()); 这样,把可能带中文的变量都encodeURI
------解决方案--------------------
探讨

引用:
忽然想起来了,你似乎还没有调试 ajax 的工具或能力
$pdo=new PDO("mysql:host=localhost;dbname=acom", "root", "abcdefghi",array(PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8"));

朋友你的PDO设置解决了问题,谢谢!
同时问一下……

------解决方案--------------------
探讨

有没有在配置文件中一次改完,不再执行该语句的方法?

------解决方案--------------------
问题解决了就好!

在实例化 PDO 时附加的参数 array(PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8")
表示的意思是:连接mysql成果后,立即执行 set names utf8 指令,即将通讯用的字符集设为 utf-8

由于 mysql 数据库都是独立的,公共的。所以打不大可能就只按你需要的参数被安装
所以使用时声明一下字符集是很有必要的

mysql 对于 PDO 就属于个性化的东西了。对于声明字符集,他需要执行 sql 指令,要是 oralce 就是在 dsn 中声明了
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn