Why does jQuery add numerical indices to arrays in GET requests with .ajax()? Is there a way to remove those?
For example, in jQuery, let’s say I send the following in as data to .ajax():
var source = {
"type": "database",
"criteria": {
"match": "all",
"rules": [{"equals": 1, "val": "test"}, {"equals": 1, "val": "two"}]
}
I want the rules var to be serialized as an array. This gets serialized as the following url that .ajax() uses:
api?source[type]=database&[criteria][rules][0][equals]=1&source[criteria][rules][0][val]=test&source[criteria][rules][1][equals]=1&source[criteria][rules][1][val]=two
Because the arrays are indexed (rules[0] and rules[1]), it gets interpreted on the server as:
"rules"=>{"0"=>{"equals"=>"1", "val"=>"test"}, "1"=>{"equals"=>"1", "val"=>"test"}}
Ack, it’s now an object! What I need is for it to be serialized as such:
api?source[type]=database&[criteria][rules][][equals]=1&source[criteria][rules][][val]=test&source[criteria][rules][][equals]=1&source[criteria][rules][][val]=two
using rules[] (no index). This then gets correctly interpreted as:
"rules"=>[{"equals"=>"1", "val"=>"test"}, {"equals"=>"1", "val"=>"test"}]
An array!
Is there a setting to control this with ajax? I’ve played around with different settings like dataType and traditional with no luck.
I’m assuming using var[] (no index) is correct as I’ve seen it in examples in jQuery documentation:
$.get("test.php", { 'choices[]': ["Jon", "Susan"]} );
I don’t believe you can change the way that jQuery does that. If I were you, I would write a quick function to generate the parameter you want from your array as a string and then tack that parameter on to the ajax request using the data property as seen below: