12

我正在尝试使用 Ajax 删除我的 Rails 模型的一个实例。

它发生在单击按钮时,我的代码如下所示:

$("#button").click(function(){ 
    $.ajax({
        type: "POST",
        url: "/slot_allocations/" + slotallocation_id,
        dataType: "json",
        data: {"_method":"delete"},
        complete: function(){
            $( "#SlotAllocationForm" ).dialog( "close" );
            alert("Deleted successfully");
        }
    });
});

我能够成功删除它,但是该delete方法始终会跟随post服务器请求以使用现有数据创建新模型。这些是对服务器的请求。

1. POST http://localhost:3000/slot_allocations/1009 [HTTP/1.1 204 No Content  57ms]    
2. POST http://localhost:3000/slot_allocations [HTTP/1.1 302 Found  111ms]
3. GET http://localhost:3000/slot_allocations/1010 [HTTP/1.1 200 OK  185ms]

#1单击我的按钮时发生。但是,我不太清楚为什么#2#3发生。

视图中有两个按钮:

<button id="button">Delete</button>
<div class="actions"><%= f.submit %></div>
4

2 回答 2

23

假设您的按钮在表单内,单击它可能会提交该表单,除了触发 ajax 请求。

您要做的是阻止单击按钮的默认操作,即提交表单。

function()将参数更改为function(event),然后添加event.preventDefault()调用:

$("#button").click(function(event){ 
    $.ajax({
        type: "POST",
        url: "/slot_allocations/" + slotallocation_id,
        dataType: "json",
        data: {"_method":"delete"},
        complete: function(){
            $( "#SlotAllocationForm" ).dialog( "close" );
            alert("Deleted successfully");
        }
    });
    event.preventDefault();
});
于 2013-02-17T17:58:19.243 回答
7

您可以使用:

type: "DELETE"

代替:

type: "POST"

并删除

data: {"_method":"delete"}
于 2013-11-07T16:10:01.117 回答