您的位置:首页 > Web前端 > JQuery

ajax(jquery)汉字乱码分析与及解决方案

2013-09-10 18:40 183 查看

相关知识回顾

jquery采用utf-8发送数据,看下v1.2.6中处理编码的代码

// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a ) {
var s = [ ];

function add( key, value ){
s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
};

// If an array was passed in, assume that it is an array
// of form elements
if ( a.constructor == Array || a.jquery )
// Serialize the form elements
jQuery.each( a, function(){
add( this.name, this.value );
});

// Otherwise, assume that it's an object of key/value pairs
else
// Serialize the key/values
for ( var j in a )
// If the value is an array then the key names need to be repeated
if ( a[j] && a[j].constructor == Array )
jQuery.each( a[j], function(){
add( j, this );
});
else
add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );

// Return the resulting serialization
return s.join("&").replace(/%20/g, "+");
}


方案一,解码全部使用utf-8编码。(这个国内一般不会如此处理)

方案二,过滤器针对 ajax部分解码采用utf-8进行转码,其余部分仍用GBK。

方案2.1 前台传递编码方式utf-8. (注意,千万不要通过parameter传递,对于tomcat、tongweb等中间件只会转码一次)

var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
xhr.setRequestHeader("charset", "utf-8");
过滤器通过请求头中的参数charset设置字符集
String charset = servletRequest.getHeader("charset");


[title2]方案2.2 通过ajax特有属性头进行判断[/title2]

if (this.xmlHttpCharacterEncoding != null
&& "XMLHttpRequest".equalsIgnoreCase(request
.getHeader("x-requested-with"))) {
request.setCharacterEncoding(this.xmlHttpCharacterEncoding);
} else if (characterEncoding != null) {
request.setCharacterEncoding(characterEncoding);
}

方案3:全部使用gbk解码。这个有二次转码的问题。

修改jquery传递参数部分,将参数转换成为unicode,encodeURI("测试001")

修改action代码String orderCode = URLDecoder.decode(request.getParameter("orderCode"),"utf-8");

至此"测试001"被编码2次:1,encodeURI;2,jquery encodeURIComponent

被解码2此:1,filter;2,action中URLDecoder.decode
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: