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

谁都会走 提交于 2019-12-03 00:59:48
Derick Bailey

@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.

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");
}});

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!