Cristian Rojas
Cristian Rojas

Reputation: 2862

Backbone.js fetch method with data option is passing URL params with square brackets

I have the following code to fetch the data for my collection but with specifying what colors should come from the server:

fruits = new FruitsCollection();
fruits.fetch({
    data: {color: ['red', 'green']}
});

This is what I expect:

http://localhost:8000/api/fruits/?color=red&color=green

This is what I got:

http://localhost:8000/api/fruits/?color[]=red&color[]=green

As you can see, for some unknown reason Backbone.js is appending the square brackets to the URL params, instead of having color=green I have color[]=green

I'm using django-rest-framework in the server side and I know I can do a hardcoded fix there, but I prefer to know the logic reason because it is happening and how can I solve it from my javascript.

Upvotes: 10

Views: 12716

Answers (1)

nemesv
nemesv

Reputation: 139778

Backbone uses jQuery.ajax under the hood for the ajax request so you need to use the traditional: true options to use "traditional" parameter serialization:

fruits = new FruitsCollection();
fruits.fetch({
    traditional: true,
    data: {color: ['red', 'green']}
});

Upvotes: 19

Related Questions