Saving data of the Backbone.js model. Data not sent correctly

I am new to Backbone.js and I am trying to save a model instance. I am using django as my server.

Client Side Code:

var Song = Backbone.Model.extend({
    defaults: {
        name: 'New Song'
    },
    url: function() {
        return window.location.href;
    }

});

var song = new Song()
song.save()

csrfmiddlewaretoken set correctly before sending data.

I stepped over the jQuery $ .ajax function, called Backbone.sync internally, and found that the model object contains the correct data.

However request.POST, received by the server,

POST:<QueryDict: {u'[object Object]': [u'']}>

instead of actual data. Any idea where I'm wrong?

Update: I quickly fixed it by setting Backbone.emulateJSONto true. But according to the comments in the Backbone code (0.9.2), it is intended for legacy servers. I am using Django 1.4.1. Does this mean that django 1.4.1 is incompatible?

2. Backbone.emulateJSON false, firefox, chrome.

   "[Exception... "Component returned failure code: 0x80460001 
(NS_ERROR_CANNOT_CONVERT_DATA)"  nsresult: "0x80460001 (NS_ERROR_CANNOT_CONVERT_DATA)"

  location: "JS frame :: http://localhost:8000/static/jquery.js :: <TOP_LEVEL> :: line 8214"  data: no]"

jQuery ajax Backbone, , jQuery.

3. , $.ajax, Backbone.sync, . - .

Backbone.js verson: 0.9.2

jQuery: 1.8.0. 1.7.2. .

+5
2

, - / . , Backbone POST JSON request.POST QueryDict. , , jyth python json.loads(request.body) Django .

, , Backbone.emulateJSON = true; , , Backbone JSON Django "legacy", request.POST QueryDict.

+9

, QueryDict.POST, Backbone.sync.

Backbone.emulateJSON true.

Backbone.sync . , .

if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
  params.contentType = 'application/json';
  params.data = JSON.stringify(options.attrs || model.toJSON(options));
}

:

if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
  params.contentType = 'application/json';
  if(options.emulateJSON){
     params.data = options.attrs || model.toJSON(options);
  }else{
     params.data = JSON.stringify(options.attrs || model.toJSON(options));
  }
}

, Backbone "model" POST QueryDict.

params.data = params.data ? {model: params.data} : {};

:

params.data = params.data ? params.data : {};

! .POST QueryDict.

+1

All Articles