html ajax中文乱码问题,ajax中文乱码问题解决方案

ajax中文乱码问题在中文中经常会出现这种问题,其实只要稍加注意就不会出现ajax中文乱码这回事情了,注意前后台编码一致.你用的是中文.而ajax传输数据的时候用的是utf-8 ,还有对ajax get方法时最好escape 或urlcode,

如果是用servlet就加

response.setcontenttype("text/html;charset=gb2312");

request.setcharacterencoding("gb2312");

还有一个更好的方法就是在加一个filter

在其中加入

response.setcontenttype("text/html;charset=gb2312");

request.setcharacterencoding("gb2312");

一切都解决了

再说一下从客户端上传数据,就必须在服务端进行编码转换

string param = request.getparamter("param");

param = new string(param.getbytes("iso-8859-1"),"gb2312");

现在就都是中文的了。

注意前后台编码一致.你用的是中文.而ajax传输数据的时候用的是utf-8

var oxmlhttp = 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.write(oxmlhttp.responsebody);

ostream.position= 0;

ostream.type= 2;

ostream.charset= "gb2312 ";

var result= ostream.readtext();

ostream.close();

ostream = null;

alert( result);

}

客户端文件的编码设置为gb2312,如下面代码所示:

html代码

在发送的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");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值