重写jquery.参数的函数
overriding the jquery.param function
我有一个问题与jQuery。参数的函数。jQuery使用+而不是%20来对空格进行url编码
var obje = {
'test': 'tester 2'
}
console.log($.param(obje));
返回"测试=测试器+ 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));
这失败了。美元的。参数没有被覆盖。
你知道怎么回事吗?
谢谢!
编辑:我的解决方案(因为我是一个新用户,我显然可能无法在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);
您需要使用$.param
而不是$.fn.param
(这将是一个调用jQuery对象的函数,例如$(...).param()
)
老帖子我知道,但为了记录知识。要替换使用$.param()时留下的'+',请考虑以下操作:
(使用您提供的代码)
var obje = {
'test': 'tester 2'
}
console.log($.param(obje).replace(/'+/g, "%20"));
这将导致:Test = test2
也可以通过在ajax设置对象中使用" beforeend "来实现"重新替换"修复:
{ beforeSend: function (request, settings) { settings.data = settings.data.replace(/'+/g, "%20"); } }
此方法适用于您实际上不想改变$.param()的原始行为的情况(例如,如果您想在url中使用"+",但在POST数据中使用"%20")。
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 为什么不'我们在javascript中使用函数参数的数据类型
- 使用闭包共享构造函数参数
- 函数参数的值错误
- 当一个重要的构造函数参数丢失时应该发生什么
- 阻止ReSharper将JavaScript函数参数放到新行中
- 根据函数参数将CSS值存储在var中,然后对其进行操作
- 使构造函数参数具有ES6类方法的特权
- 当客户端将两个按钮的javascript函数参数修改为相同时,SQL/PHP会更新多行
- Windows.Networking.EndpointPair构造函数参数
- 是否可以使用Sinon.JS检查函数参数绑定是否正确
- 大括号中的Javascript函数参数
- jQuery 无法使用 AJAX 调用访问函数内部的函数参数
- 将JSON字符串转换为函数参数
- eval()读取函数参数有多糟糕
- Javascript不能在一个命令中使用函数参数
- 函数参数在内部不可见,返回新的Promise(函数(resolve,reject).传递给被promise化的函数的
- ES6类构造函数参数
- 是否可以在javascript函数参数列表中调用多个函数