gpt4 book ai didi

javascript - Backbone model.destroy() 调用错误回调函数,即使它工作正常?

转载 作者:IT王子 更新时间:2023-10-29 03:12:18 32 4
gpt4 key购买 nike

我有一个 Backbone.js当用户单击模型 View 中的链接时我试图销毁的模型。 View 是这样的(伪代码,因为它是在 CoffeeScript 中实现的,可以在问题的底部找到)。

var window.ListingSaveView = Backbone.View.extend({
events: {
'click a.delete': 'onDestroy'
},

onDestroy: function(event){
event.preventDefault();
this.model.destroy({
success: function(model, response){
console.log "Success";
},
error: function(model, response){
console.log "Error";
}
});
}
});

当我在浏览器中单击删除链接时,我总是将错误记录到控制台,即使我的服务器记录了关联数据库记录的成功销毁并返回200 响应。当我刷新页面(导致集合从数据库重新呈现)时,我删除的模型将消失。

一个有趣的是,当我在错误回调中记录 response 时,它的状态码 200 表示成功,但它也报告 statusText: "parseerror" 不管是什么意思。我的服务器日志中没有错误。

我做错了什么?

这是服务器的响应:

  Object
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
isRejected: function () {
isResolved: function () {
overrideMimeType: function ( type ) {
pipe: function ( fnDone, fnFail ) {
promise: function ( obj ) {
readyState: 4
responseText: " "
setRequestHeader: function ( name, value ) {
status: 200
statusCode: function ( map ) {
statusText: "parsererror"
success: function () {
then: function ( doneCallbacks, failCallbacks ) {
__proto__: Object

这是销毁与(Ruby on Rails)交互的服务器操作

  # DELETE /team/listing_saves/1.json
def destroy
@save = current_user.team.listing_saves.find(params[:id])
@save.destroy
respond_to do |format|
format.json { head :ok }
end
end

对于那些喜欢它的人来说,这里是 Backbone View 的实际 CoffeeScript 实现:

class MoveOutOrg.Views.ListingSaveView extends Backbone.View
tagName: 'li'
className: 'listing_save'
template: JST['backbone/templates/listing_save']
events:
'click a.delete_saved': 'onDestroy'

initialize: ->
@model.bind 'change', this.render
render: =>
renderedContent = @template(@model.toJSON())
$(@el).html(renderedContent)
this
onDestroy: (event) ->
event.preventDefault() # stop the hash being added to the URL
console.log "Listing Destroyed"
@model.destroy
success: (model, response)->
console.log "Success"
console.log model
console.log response

error: (model, response) ->
console.log "Error"
console.log model # this is the ListingSave model
console.log response

最佳答案

@David Tuite 评论:

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

仅供引用 - 当您进行销毁时,您不需要返回被销毁模型的完整 json。你可以返回一个空的 json 散列,它会工作得很好。您唯一需要为模型返回 json 的时间是在保存/更新时。

关于javascript - Backbone model.destroy() 调用错误回调函数,即使它工作正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7305079/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com