What Does traditional Do in jQuery $.param?
The traditional parameter in jQuery's
$.param() method controls how arrays and nested objects are
serialized into query strings. By default, jQuery uses a deep, recursive
serialization method introduced in jQuery 1.4, which appends square
brackets [] to array keys. Enabling the
traditional parameter reverts serialization back to the
shallow method used in jQuery 1.3, stripping the brackets and repeating
keys for array items, which ensures compatibility with backend
frameworks that do not support square bracket query notation.
The Default Behavior
(traditional: false)
In modern jQuery, $.param() defaults to recursive
serialization (traditional: false). This is designed to
support complex data structures, including nested objects and
multidimensional arrays, by using bracket notation suitable for
frameworks like Ruby on Rails and PHP.
When serializing an array:
$.param({ items: ["apple", "banana"] }, false);
// Output: "items%5B%5D=apple&items%5B%5D=banana"
// Decoded: "items[]=apple&items[]=banana"When serializing a nested object:
$.param({ user: { name: "John", age: 30 } }, false);
// Output: "user%5Bname%5D=John&user%5Bage%5D=30"
// Decoded: "user[name]=John&user[age]=30"The Traditional
Behavior (traditional: true)
Setting traditional to true switches
$.param() to shallow serialization. Under this mode:
- Arrays omit brackets: Instead of appending
[], the key name is simply repeated for each array element. - Nested objects are not serialized recursively: Any
nested object is converted using its
.toString()method, typically resulting in[object+Object].
When serializing an array with traditional: true:
$.param({ items: ["apple", "banana"] }, true);
// Output: "items=apple&items=banana"When serializing a nested object:
$.param({ user: { name: "John" } }, true);
// Output: "user=%5Bobject+Object%5D"
// Decoded: "user=[object Object]"When to Use
traditional: true
You should set traditional: true when communicating with
servers or APIs that expect arrays to be passed as repeated query
parameters without brackets. Common scenarios include:
- Backends built with Java (e.g., Spring or Servlet containers),
Python/Django, or ASP.NET, where query binding often expects
key=val1&key=val2instead ofkey[]=val1&key[]=val2. - Interacting with legacy endpoints that were built during the jQuery 1.3 era or earlier.
Using it in AJAX Requests
The parameter is commonly configured directly within
$.ajax() calls via the traditional option:
$.ajax({
url: "/api/search",
type: "GET",
data: { tags: ["tech", "news"] },
traditional: true
});To enable shallow serialization across all requests in an application, configure it globally:
jQuery.ajaxSettings.traditional = true;