Rails Ajax Jquery Delete之后提交Post请求

But*_*eer 11 ajax jquery ruby-on-rails ruby-on-rails-3

我试图用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");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我能够成功删除它,但是该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]
Run Code Online (Sandbox Code Playgroud)

#1发生在点击我的按钮上.不过,我也不太清楚为什么#2#3发生.

视图中有两个按钮:

<button id="button">Delete</button>
<div class="actions"><%= f.submit %></div>
Run Code Online (Sandbox Code Playgroud)

Dyl*_*kow 22

假设您的按钮位于表单内,单击它可能除了触发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();
});
Run Code Online (Sandbox Code Playgroud)

  • 你用`data:{"_ method":"delete"},......部分来拯救我的生命.+1! (3认同)

小智 6

您可以使用:

type: "DELETE"
Run Code Online (Sandbox Code Playgroud)

代替:

type: "POST"
Run Code Online (Sandbox Code Playgroud)

并删除

data: {"_method":"delete"}
Run Code Online (Sandbox Code Playgroud)