Ajax中文数据乱码问题。
1、向服务器发送请求数据在服务器端必须经过内码转换才行。
转换代码: String value = request.getParmater("key"); value = new String(value.getBytes("ISO8859_1"),"GBK"); //value已经由默认内码转换位GBK了 |
我遇到的问题就是在发送异步请求时,url参数里有中文:var url = "UserChecked?user="+user;
其中user值为中文,但是发送到服务端Servlet中接收该参数时就成乱码了,当然各种网上提到的解决方法都试过了,包括什么建立过滤器(失败),js函数数据封装,就是encodeURIComponent()等这些函数,个人觉得上面我列出的方法是解决该问题的最好方法咯 。
2、服务器端向客户端写数据时,需要设置数据格式和内码才行。
设置代码: response.setContentType("text/html"); response.setCharacterEncoding("GBK"); |
*******************************************************
网上其他一些解决方法或解释:
*****************************************************
ajax 是依靠xmlHttpRequest 对象来异步发送请求
造成乱吗肯定是由于中文编码和http头中的编码 不一致
默认在http头中找不到编码的话 xmlhttprequest对象是把字符按照utf-8来处理的 如果你设置了http头的编码的话 就会按照你设置的类型来编码.
解决返回数据的乱吗问题可能在jsp的servlet里面这样设置
response.setHeader("charset", "gb2312");
解决发送的请求后台处理的时候乱码需要 设置xmlhttprequest对象发送请求时候的编码. 在prototype中的编码设置 是这样
new Ajax.Request(
'test',
{
onSuccess:function(r){},
encoding :'UTF-8'//和你的提交的编码一直
}
);
**********************************************
发送请求中文乱码问题
那么在action或者servlet中如何获取这个name,如果不作任何处理。。。接收到的可能是乱码....
解决方案:
在js中:
//发送请求,传递用户输入的name到库中去检测
function checkName(obj){
obj.className='text';
//用encodeURIL方法进行编码
var name=encodeURI(obj.value);
name=encodeURI(name);
//alert("编码后的值为:"+name);
sendAjaxRequest("/LhCard/GeRen/uholdcard.do?method=checkname", "name", name, showresult);
}
在action或者servlet中解密:
String name = request.getParameter("name");
try {
name = java.net.URLDecoder.decode(name, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}