I'm creating a backbone app that's connecting to a RESTful backend. When I call save() on a model, it sends the post data as stringified JSON:
{"firstName":"first","lastName":"last","Email":"[email protected]"}
but my server expects it to be formatted like a querystring:
firstName=first&lastName=last&[email protected]
is there a way to have backbone send it differently?
Backbone doesn't provide anything like this out of the box.
But is easy to override and customize it to your needs.
Have a look to the source code: http://documentcloud.github.com/backbone/docs/backbone.html
and check out that calling save
, it will trigger a sync
call in the background.
So what you need is to override Backbone.sync
function with your own.
I would modify the part of:
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
with
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = $.param(model); // <-- CHANGED
}
Notice I'm using jQuery param
If you want to use a custom function, check this question: Query-string encoding of a Javascript Object
[Update.]
No need to modify directly. Better override it with your own function 'Backbone.sync'
Check the "TODO" example of the Backbone repository. It has a localStorage.js
file that overrides Backbone.sync function https://github.com/documentcloud/backbone/tree/master/examples