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

Cristian Rojas picture Cristian Rojas · Aug 28, 2013 · Viewed 12.6k times · Source

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.

Answer

nemesv picture nemesv · Aug 28, 2013

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']}
});