论坛首页 Web前端技术论坛

ajax post 编码 乱码问题的解决方法

浏览 5812 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-01-27   最后修改:2010-01-27

用ajax提交表单,经常会遇到编码的问题,后台要特殊处理比较麻烦。

今天在网上找了一下,发现jquery prototype等流行的框架也不能很好的解决gbk编码下的乱码问题。

先看几个基本概念:

escape 方法
对 String 对象编码以便它们能在所有计算机上可读,

escape(charString)

必选项 charstring 参数是要编码的任意 String 对象或文字。

说明
escape 方法返回一个包含了 charstring 内容的字符串值( Unicode 格式)。所有空格、标点、重音符号以及其他非 ASCII 字符都用 %xx 编码代替,其中 xx 等于表示该字符的十六进制数。例如,空格返回的是 "%20" 。

字符值大于 255 的以 %uxxxx 格式存储。

注意   escape 方法不能够用来对统一资源标示码 (URI) 进行编码。对其编码应使用 encodeURI 和encodeURIComponent 方法。
========================
encodeURI 方法
将文本字符串编码为一个有效的统一资源标识符 (URI)。

encodeURI(URIString)

必选的 URIString 参数代表一个已编码的 URI。

说明
encodeURI 方法返回一个编码的 URI。如果您将编码结果传递给 decodeURI,那么将返回初始的字符串。encodeURI 方法不会对下列字符进行编码:":"、"/"、";" 和 "?"。请使用 encodeURIComponent 方法对这些字符进行编码。

=======================
encodeURIComponent 方法
将文本字符串编码为一个统一资源标识符 (URI) 的一个有效组件。

encodeURIComponent(encodedURIString)

必选的 encodedURIString 参数代表一个已编码的 URI 组件。

说明
encodeURIComponent 方法返回一个已编码的 URI。如果您将编码结果传递给 decodeURIComponent,那么将返回初始的字符串。因为 encodeURIComponent 方法对所有的字符编码,请注意,如果该字符串代表一个路径,例如 /folder1/folder2/default.html,其中的斜杠也将被编码。这样一来,当该编码结果被作为请求发送到 web 服务器时将是无效的。如果字符串中包含不止一个 URI 组件,请使用 encodeURI 方法进行编码。

=========================

再看一下jquery的处理源码:

function add( key, value ){
			// If value is a function, invoke it and return its value
			value = jQuery.isFunction(value) ? value() : value;
			s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
		}
// Return the resulting serialization
		return s.join("&").replace(/%20/g, "+");

 

把key和value都encodeURIComponent了,最后还把%20替换成+

解决办法:在原来基础上再包裹一层encodeURIComponent

encodeURIComponent(encodeURIComponent(value)

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

 后台解码:java.net.URLDecoder.decode(request.getParameter("name"), "UTF-8″);

 

===========================================

再看一下prototype的处理源码:

$H(extras).each(function(pair) { headers[pair.key] = pair.value });

function $H(object) {
  return new Hash(object);
};

function toQueryPair(key, value) {
    if (Object.isUndefined(value)) return key;
    return key + '=' + encodeURIComponent(String.interpret(value));
  }

toQueryString: function() {
      return this.map(function(pair) {
        var key = encodeURIComponent(pair.key), values = pair.value;

        if (values && typeof values == 'object') {
          if (Object.isArray(values))
            return values.map(toQueryPair.curry(key)).join('&');
        }
        return toQueryPair(key, values);
      }).join('&');
    },

 

在prototype的函数中,会把key和value分别用encodeURIComponent 来把一个字符串转成utf-8的URL编码形式.

比如,"中文"会被编码成:%E4%B8%AD%E6%96%87

但该字符串传到后台时,会被识别成乱码. 用request.getParameter取到的字符串也是乱码,而不是本身的字符。

主要原因是%号,如果该串改成%22E4%22B8%22AD%22E6%2296%2287 也是可以识别的.

解决方法: 在prototype文件中找到 encodeURIComponent? 这段, 在encodeURIComponent 后,再将该字符串用escape方法再编码一次。
这时候传到后台,用request.getParameter,可以得到编码后的正确的字符串。即 %E4%B8%AD%E6%96%87 .
用java.net.URLDecoder.decode(keyword,"UTF-8"); 对这个字符串进行解码,从而得到正确的中文。

 

====================================

 

 总的解决办法:对中文(value)进行编码即可。如果页面和js都是utf-8还可以不用encodeURIComponent。

最后发布下coos脚本库的综合解决办法:

coos.ajax.encode = function(str,encode)
{
	//str为空或不用编码则直接返回
	if (str == null || str == "" || encode=="unencode")
	{
		return str;
	}
	var value = "";
	//value编码采用和jquery一样的处理方式
	//后台解码:java.net.URLDecoder.decode(request.getParameter("name"), "UTF-8″)
	if(encode == "text")
	{
		value = str.replace(/\n|\r/g,"");//去掉换行符号
		value = value.replace(/<\/?.+?>/g,"");//去掉HTML标签
		value = encodeURIComponent(encodeURIComponent(value)).replace(/%20/g, "+");
	}
	else
	{
		value = encodeURIComponent(encodeURIComponent(value)).replace(/%20/g, "+");
	}
	/*//以前自定义的方法,由于后台没有统一的解码方式,不推荐使用
	else
	{
		value = escape(str);
		//替换+号为%2B
		value = value.replace(/\+/g, "%2B");
		//替换%号为%25如"%u2a2a dfd %u1f1f";替换后为%25u2a2a dfd %25u1f1f
		value = value.replace(/%u([0-9A-F]{4})/ig,function(word){return escape(word);});
	}

	java后端没有直接的解码函数,自定义方法为:
	public static String unescape (String str)
	{
		if (str == null)
			return null;
		
		String regEx="%u([0-9A-F]{4})";
		Pattern p=Pattern.compile(regEx);
		Matcher m=p.matcher(str);
		
		StringBuffer sb = new StringBuffer();
		
		while (m.find ())
		{
			String group = m.group ().substring(2);
			m.appendReplacement(sb, String.valueOf((char)(Integer.parseInt(group,16)))); 
		}
		
		m.appendTail(sb);
		
		return sb.toString();
	}
	 	*/
	return value;
};

 

论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics