在对一个老的项目添加新功能,需要用到jquery1.11,以前用的都是jquery1.3.2。升级到1.11.1以后,发现通过$.post提交数组,参数名称会自动加一个[],搜百度,找到一些方案,单都不是很好,需要改动原来的代码,无奈大致看了下 jquery1.11.1部分的代码。找到ajax相关的代码。
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
最好的解决方案是:
1 先在页面导入jquery
2 在script 标签中写
jQuery.ajaxSettings.traditional = true;
然后 $.post提交数组就正常了。