200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > ajax中文乱码问题解决方案

ajax中文乱码问题解决方案

时间:2023-10-05 10:55:28

相关推荐

ajax中文乱码问题解决方案

今天给大家分享的是由小编精心为您推荐的ajax中文乱码问题解决方案,喜欢的朋友可以分享一下,也算是给小编一份支持,大家都不容易啊!

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

代码如下:

%@ page contenttype="text/html;charset=gb2312%

如果是用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

代码如下:

script

var oxmlhttp = new activexobject( "microsoft.xmlhttp ");

oxmlhttp.open( "get ", "/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);

}

/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");

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。