重写jquery.参数的函数

overriding the jquery.param function

本文关键字:函数 参数 jquery 重写      更新时间:2023-09-26

我有一个问题与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")。

[编辑,因为我记得string.replace()将只匹配一次,除非它是一个带有g标志的regex对象]