简体   繁体   中英

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"

This seems to be the defined behaviour since version 1.14.

在此处输入图像描述

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM