我正在尝试使用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>
data: {"_method":"delete"}
的背景信息,请参考如何使用PATCH、PUT或DELETE方法的表单? -- Rails框架鼓励您的应用程序采用RESTful设计... 然而,大多数浏览器在提交表单时只支持GET
和POST
方法。Rails通过模拟其他方法的方式来解决这个问题,它会在名为_method
的隐藏输入中设置所需的方法。 - user664833