Backbone model.destroy() invoking error callback function even when it works fine?

后端 未结 5 1253
不知归路
不知归路 2021-02-05 01:01

I have a Backbone.js model that I\'m trying to destroy when the user clicks a link in the model\'s view. The view is something like this (pseudocode because it\'s implemented in

相关标签:
5条回答
  • 2021-02-05 01:39

    I had this same problem. In my delete method on the server (java), I didn't return anything. Just status 200/OK (or 204/No content). And so the "parsererror" problem was caused by jquery trying to convert the empty response into JSON, which failed (since "json" is the default data type).

    My solution was to use the "text" dataType instead, which can be set in the options:

    model.destroy({ dataType: "text", success: function(model, response) {
      console.log("success");
    }});
    
    0 讨论(0)
  • 2021-02-05 01:45

    Using the Slim Framework on an LAMP server you can add a Response Status to DELETE routes (or custom routes that don't return anything)

    $app->response()->status(204);//204 No Content

    this also sets the Content-Type back to text/html to allow for the empty body

    0 讨论(0)
  • 2021-02-05 01:51

    @David Tuite comment:

    "Ok I figured it out. It seems that Backbone expects the JSON response to be a JSON serialization of the record that was destroyed. However, Rails controller generators only return head :ok by default. I changed my JSON response to be render json: @listing_save where @listing_save is the record I just destroyed and it registers a success."

    FYI - when you're doing a destroy, you don't need to return the full json for the destroyed model. you can return an empty json hash and it will work just fine. the only time you need to return the json for the model is on a save / update.

    0 讨论(0)
  • 2021-02-05 02:00

    Are you sure of your URL ? Do you append a .json at the end of the Backbone.Model url ? Since you check this on your server side (respond_to do |format| ... end), you might not send the correct head :ok response

    Try with this destroy rails method to test if this is the problem :

    def destroy
      @save = current_user.team.listing_saves.find(params[:id])
      @save.destroy
      head :ok
    end
    
    0 讨论(0)
  • 2021-02-05 02:03

    Your response must have status code 204 as you won't return any content. Since backbone uses a REST interface you should return different http status codes depending on the task.

    0 讨论(0)
提交回复
热议问题