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

来源:互联网 发布:淘宝买家怎么升心快 编辑:程序博客网 时间:2024/05/20 05:22

相关知识回顾

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

// Serialize an array of form elements or a set of// key/values into a query stringparam: 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 elementsif ( a.constructor == Array || a.jquery )// Serialize the form elementsjQuery.each( a, function(){add( this.name, this.value );});// Otherwise, assume that it's an object of key/value pairselse// Serialize the key/valuesfor ( var j in a )// If the value is an array then the key names need to be repeatedif ( a[j] && a[j].constructor == Array )jQuery.each( a[j], function(){add( j, this );});elseadd( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );// Return the resulting serializationreturn 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");

方案2.2 通过ajax特有属性头进行判断

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