简体   繁体   中英

backbone model save not working

I tried to use Backbone.js model to sync data with the server. However the save method doesn't work. Any one can help me to find out why?

The following code works (not using Backbone model):

var newComment = {
    user: user,
    createdDate: date,
    content: text
  }

  //TODO send ajax post request to record the data

  $.ajax({
    url: "comment.php",
    context: document.body,
    data: newComment,
    type: 'POST'
  }).done(function(resp) {
    console.log("resp", resp);
  });

The code not working:

var Comment = Backbone.Model.extend({
     urlRoot: 'comment.php'
  });

var comment = new Comment();
comment.save({content: text, dsm_line_item_id: "49934380"}, {
    succcess: function(model, resp, opt) {
          console.log("successfully saved" + resp);
        },
    error: function(model, resp, opt) {
          console.log("error", resp);
        }
    })
succcess: function(model, resp, opt) {

is this a typo

Supposed to be success: function(model, resp, opt) {

This is a guess, but I think that it might be the answer. Backbone's save delegates to Backbone.sync , the function that Backbone uses to read or save models to the server.

Backbone uses POST, GET, DELETE and PUT; but some servers have problems with PUT and DELETE. Maybe your server has a problem with PUT and that's why your code isn't working.

You could try with Backbone.emulateHTTP = true; . That option allows you to work with legacy web servers that don't support Backbone's RESTful approach. The PUTs and DELETEs will be subsituted with POSTs during the sync.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM