Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 465
Cristian Rojas Avatar asked Aug 28 '13 15:08

Cristian Rojas


1 Answers

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']}
});
like image 200
nemesv Avatar answered Sep 20 '22 12:09

nemesv