脚本宝典收集整理的这篇文章主要介绍了ajax中文乱码问题解决方案,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
ajax中文乱码问题在中文中经常会出现这种问题,其实只要稍加注意就不会出现ajax中文乱码这回事情了,注意前后台编码一致.你用的是中文.而ajax传输数据的时候用的是utf-8 ,还有对ajax get方法时最好esca
PE 或urlcode,
<%@ page contenttype="text/ht
ML;charset=gb2312%>
如果是用servlet就加
response.setcontenttype("text/html;charset=gb2312");
request.setcharacterencoding("gb2312");
还有一个更好的方法就是在加一个filter
在其中加入
response.setcontenttype("text/html;charset=gb2312");
request.setcharacterencoding("gb2312");
一切都解决了
再说一下从客户端上传数据,就必须在服务端进行
编码转换 string par
am = request.getparamter("param");
param = new string(param.getbytes("iso-8859-1"),"gb2312");
现在就都是中文的了。
注意前后台编码一致.你用的是中文.而ajax传输数据的时候用的是utf-8
<script>
VAR o
XMlhttp = new activexobject( "microsoft.xmlhttp ");
oxmlhttp.open( "get ", "http://dotnet.aspx.cc/content.aspx ", false);
oxmlhttp.send()
var ostream = new activexobject( "adodb.stream ");
if(ostream
== null)
alert( "您的机器不支持adodb.stream. ")
else
{
ostream.type=1;
ostream.mode=3;
ostream.open() ;
ostream.wr
ITe(oxmlhttp.responsebody);
ostream.position= 0;
ostream.type= 2;
ostream.charset= "gb2312 ";
var result= ostream.readtext();
ostream.close();
ostream = null;
alert( result);
}
</script>
客户端文件的编码设置为gb2312,如下面代码所示:
html代码
<
;meta http-equiv="content
-type" content="text/html; charset=gb2312" />
在发送的
url地址中的查询字符串
或者是使用post方式发送的请求内容不要使用escape函数进行编码,切记!
在
服务器端的jsp教程文件也设置为gb2312
编码格式,如下面代码所示:
jsp 代码
或者设置response的头,如下面代码所示:
response.setheader("content-type","text/html; charset=gb2312");
两者原理是一样的。
最着关键的是在获取参数时
应该对获取字符串进行重新编码,如下面代码所示:
string username = new string(request.getparameter("username").getbytes("iso8859_1"),"gb2312");
其中,username为接收的参数。
直接使
用Out.
PRint(username);就可以将中文返回给客户端,在客户端直接使用xmlhttp.responsetext属性就可以直接使用返回的中文了!
附件中我测试用的一个小例子,在tomcat6.0和resin2.1.8中通过测试!
其实,还有一个一劳永逸的解决
方案,就是添加一个过滤器。
补充一下提交方法为get时时在服务器里写的时这句代码
string username = new string(request.getparameter("username").getbytes("iso8859_1"),"gb2312");
为post时应该时这样吧
string username = new string(request.getparameter("username").getbytes("iso8859_1"),"utf-8");
脚本宝典总结
以上是脚本宝典为你收集整理的ajax中文乱码问题解决方案全部内容,希望文章能够帮你解决ajax中文乱码问题解决方案所遇到的问题。
如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。