今天试了一下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了。
一点拙见,高手见笑了
本文探讨了使用jQuery 1.4.2版本进行AJAX传输时出现乱码的原因,主要由于jQuery.param()方法的变化导致序列化结果不同。文章提供了两种解决方案:一是直接修改jQuery源码避免不必要的编码;二是通过后台过滤器处理字符编码。
162

被折叠的 条评论
为什么被折叠?



