10

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.

Cristian Rojas
  • 2,746
  • 7
  • 33
  • 42

1 Answers1

19

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']}
});
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • Worked as expected, this is the answer I wanted. But another question appeared, how you found this option? I can't see it in the documentation. – Cristian Rojas Aug 28 '13 at 16:00
  • 1
    In the backbone documentation it is described at the `fetch` method: http://backbonejs.org/#Collection-fetch that you can pass in any of the jQuery.ajax options and the `traditional` from the jquery documentation: http://api.jquery.com/jQuery.ajax/ – nemesv Aug 28 '13 at 18:53