一、问题描述
web端通过ajax提交参数到php服务端获取关键词模糊匹配查询结果,在火狐等浏览器版本一切正常,但在ie中提交参数到后台发生乱码现象,如下图所示:
<?php@b@ $q=$_GET["q"]; @b@ $con = mysql_connect('localhost', 'my1535594', '123456'); @b@ if (!$con){@b@ die('Could not connect: ' . mysql_error());@b@ } @b@ mysql_select_db("my1535594", $con); @b@ @b@ $sql="SELECT * FROM PMS_REP_VIEW WHERE TITLE LIKE '%".$q."%'";@b@ @b@ mysql_query("SET NAMES 'UTF8'",$con);@b@ mysql_query("SET CHARACTER SET UTF8",$con);@b@ mysql_query("SET CHARACTER_SET_RESULTS=UTF8'",$con);@b@ @b@ $result = mysql_query($sql,$con);@b@ $num_rows = mysql_num_rows($result);@b@ echo "<p >搜索结果:</p>";@b@ if ($num_rows==0){ @b@ echo "<p ><ul><li><font>没有查询结果,请确认关键词后,重试!!!</font></li></ul></p>"; @b@ }else{ @b@ while($row = mysql_fetch_array($result)){@b@ echo "<p class="s_list" >";@b@ echo "<ul>";@b@ echo "<li class="s_tit">◆ " . $row['TITLE']. "</li>";@b@ echo "<li class="s_zy" > <font>" . $row['ZHAIYAO'] . "</font></li>"; @b@ echo "</ul>";@b@ echo "</p>";@b@ } @b@ } @b@ mysql_close($con); @b@?>
二、解决方法
直接修改服务端php接收参数处理转换代码(部分截图如下,完整代码参见上面)
上图红框代码如下,请参考
if ($q != '') {@b@ $encode =mb_detect_encoding($q,array("ASCII","UTF-8","GB2312","GBK","BIG5","ISO-8859-1"));@b@ if ($encode != "UTF-8") {@b@ $q = iconv ( "gb2312","UTF-8",$q);@b@ }@b@}
结果如下图所示:
另一种方式直接把中文参数先转为十六进制伪码,再在后台进行解密,相关文章可以参考"解决URL传递中文时出现乱码问题(三种解决方法)"
客户端javascript加密代码
<script>@b@ encodeURI(str);//对应解密decodeURI("%D7%94%E5%S5%BA%B4");@b@</script>
服务端php解密代码
<?php@b@ iconv("utf-8","gb2312",urldecode("%D7%94%E5%S5%BA%B4"));@b@ @b@ //对应加密urlencode(iconv("gb2312", "UTF-8",str));@b@?>