jquery1.4使用ajax方法时需要注意:序列化方法jQuery.param() 的变化

今天试了一下jquery1.4,我用的版本是jquery-1.4.2.js,在进行ajax传输时发现老是出现乱码,郁闷了好久,网上搜了一下,才知道原来是jquery-1.4中jQuery.param() 方法有一些变化:

参考 http://www.hackhome.com/InfoView/Article_208618_2.html

之前对于{foo: ["bar", "baz"]}序列化后的结果是“foo=bar&foo=baz”,而现在是“foo[]=bar&foo[]=baz”。

见源码5405行-5433行

function buildParams( prefix, obj ) {
	if ( jQuery.isArray(obj) ) {
		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || /\[\]$/.test( prefix ) ) {
				// Treat each array item as a scalar.
				add( prefix, v );
			} else {
				// If array item is non-scalar (array or object), encode its
				// numeric index to resolve deserialization ambiguity issues.
				// Note that rack (as of 1.0.0) can't currently deserialize
				// nested arrays properly, and attempting to do so may cause
				// a server error. Possible fixes are to modify rack's
				// deserialization algorithm or to provide an option or flag
				// to force array serialization to be shallow.
				buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v );
			}
		});
					
	} else if ( !traditional && obj != null && typeof obj === "object" ) {
		// Serialize object item.
		jQuery.each( obj, function( k, v ) {
			buildParams( prefix + "[" + k + "]", v );
		});
			
	} else {
		// Serialize scalar item.
		add( prefix, obj );
	}
}

 

这下就知道为什么出现乱码了,因为在jquery源码中jQuery.param()方法是会进行字符编码的,在源码5436行:

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);
}

 

 

 

这里的中括号“[”,“]”就变成了“%5B”,“%5D”。

 

解决的方法有两个

一、既然是编码不对,那就干脆不让他编码,索性把源码中的5439行

s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
改为

s[ s.length ] = key + "=" + encodeURIComponent(value);

 

二、前面方法能解决这个问题,不过修改了jquery源码,可能会有不良影响,那我们还可以在后台使用过滤器进行字符编码处理,这样就ok了。

 

一点拙见,高手见笑了

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值