我在使用jQuery.param函数时遇到了问题。 jQuery使用“+”而不是“%20”来对空格进行URL编码。
var obje = {
'test': 'tester 2'
}
console.log($.param(obje));
返回值为"test=tester+2"
所以我考虑重写这个核心函数:
(function($){
$.fn.param = function( a, traditional ) {
console.log('custom $.param');
var s = [],
add = function( 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 );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = 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 ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
return s.join("&");
// Return the resulting serialization
//return s.join( "&" ).replace( r20, "+" );
};
})(jQuery);
var obje = {
'test': 'tester 2'
}
console.log($.param(obje));
然而,这个方法失败了... $.param 没有被覆盖。
有什么想法是错的吗?
谢谢!
编辑:我的解决方案(因为我是新用户,显然8小时内不能回答自己的问题(为什么?))
使用 ThiefMaster 的解决方案后,我仍然有一个问题,即 buildParams 未定义。 我通过调用旧函数,然后将 + 替换为 %20 来解决这个问题。
// modification of the jQuery.param function: spaces are encoded by jQuery.param with + instead of %20. replace these back to %20
(function($, oldFunction){
$.param = function( a, traditional ) {
var s = oldFunction.apply(oldFunction,[a,traditional]);
// Return the resulting serialization
return s.replace( '+', '%20' );
};
})(jQuery,jQuery.param);