Note that there are some explanatory texts on larger screens.

plurals
  1. POoverriding the jquery.param function
    primarykey
    data
    text
    <p>I have a problem with the jQuery.param function. jQuery uses + instead of %20 to URL-encode spaces</p> <pre><code>var obje = { 'test': 'tester 2' } console.log($.param(obje)); </code></pre> <p>returns "test=tester+2"</p> <p>so I thought about overriding this core function:</p> <pre><code>(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 &lt;= 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 &amp;&amp; !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("&amp;"); // Return the resulting serialization //return s.join( "&amp;" ).replace( r20, "+" ); }; })(jQuery); var obje = { 'test': 'tester 2' } console.log($.param(obje)); </code></pre> <p>This fails however.. The $.param isn't overridden.</p> <p>Any idea what can be wrong?</p> <p>Thanks!</p> <p>Edit: my solution (because I'm a new user I appearently may not answer my own question in 8 hours (Why is that?))</p> <p>With the solution of ThiefMaster I still had the problem that buildParams is undefined. I solved this by calling the old function and then replacing the + back to %20</p> <pre><code>// 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); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload