Why does the jQuery function param postfix the elements of an array with []

When using $.param to convert an array to a query string the generated elements are postfixed with []. Why is this the case and can I prevent this?

$.param({p: [1, 2]}); -> "p%5B%5D=1&p%5B%5D=2"

65 thoughts on “Why does the jQuery function param postfix the elements of an array with []”

  1. This seems to be the defined behaviour since version 1.14.

    enter image description here

    It was changed because multiple URL encoded parameters with the same name can cause conflits. So the key name of each value is used as the subscription argument in the serialized string:

    var myObject = {
      a: {
        one: 1,
        two: 2,
        three: 3
      }
    };
    console.log(decodeURIComponent( $.param( myObject ) ));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    The array has no keys, so the subscription remains empty:

    var myObject = {
      b: [ 1, 2, 3 ]
    };
    console.log(decodeURIComponent( $.param( myObject ) ));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    You can set the "traditional" argument to true to emulate the behaviour of jQuery from before 1.14.

    console.log($.param({p: [1,2]}, true ));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    Or you can write your own array serialization function.

    function serializeArray(parameter, arr){
      var serialized = "";
      for(var i = 0; i < arr.length; i++){
        serialized += parameter + "[" + i + "]=" + arr[i];
        if(i + 1 < arr.length) serialized += "&";
      }
      return serialized;
    }
    
    console.log(serializeArray("p", [1, 2]));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Reply
  2. I have been exploring for a little for any high quality articles or blog posts in this sort of house .
    Exploring in Yahoo I at last stumbled upon this web site.

    Studying this info So i’m glad to convey that I’ve an incredibly just right uncanny feeling I discovered
    just what I needed. I such a lot unquestionably will make sure to don?t
    overlook this web site and give it a glance regularly. https://www.herpessymptomsinmen.org/where-to-buy-hydroxychloroquine/

    Reply

Leave a Comment