我想删除我的Rails模型与阿贾克斯的一个实例。
它发生在一个按钮的点击,我的code如下图所示:
$(#键)。点击(函数(){
$阿贾克斯({
键入:POST,
网址:/ slot_allocations /+ slotallocation_id,
数据类型:JSON,
数据:{_method:删除},
完成:函数(){
$(#SlotAllocationForm).dialog(亲密);
警报(删除成功);
}
});
});
我能够成功地将其删除,但是删除
方法总是跟进一个后
请求服务器创建与现有数据的新模式。这些是对服务器的请求。
1。 POST HTTP://本地主机:3000 / slot_allocations / 1009 [HTTP / 1.1 204无内容57ms]
2. POST HTTP://本地主机:3000 / slot_allocations [HTTP / 1.1 302找到111ms]
3. GET HTTP://本地主机:3000 / slot_allocations / 1010 [HTTP / 1.1 200 OK 185ms]
1
发生在我点击按钮。不过,我也不太清楚为什么 2
和#3
出现。
有视图中的两个按钮:
<按钮ID =按钮>删除< /按钮>
< DIV CLASS =行动><%= f.submit%>< / DIV>
解决方案
假设你的按钮是一个形式里面,点击它可能提交的形式,除了射击Ajax请求。
您想要做什么是prevent点击按钮,该按钮提交表单的默认操作。
更改函数()
参数函数(事件)
,然后添加一个 。事件preventDefault()
电话:
$(#键)。点击(函数(事件){
$阿贾克斯({
键入:POST,
网址:/ slot_allocations /+ slotallocation_id,
数据类型:JSON,
数据:{_method:删除},
完成:函数(){
$(#SlotAllocationForm).dialog(亲密);
警报(删除成功);
}
});
。事件preventDefault();
});
I am trying to delete an instance of my Rails model with Ajax.
It happens on the click of a button and my code is as shown below:
$("#button").click(function(){
$.ajax({
type: "POST",
url: "/slot_allocations/" + slotallocation_id,
dataType: "json",
data: {"_method":"delete"},
complete: function(){
$( "#SlotAllocationForm" ).dialog( "close" );
alert("Deleted successfully");
}
});
});
I am able to delete it successfully, however the delete
method is always followed up by a post
request to the server to create a new model with the existing data. These are the requests to the server.
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
happens on the click of my button. However, I am not too sure why #2
and #3
occur.
There are two buttons in the view:
<button id="button">Delete</button>
<div class="actions"><%= f.submit %></div>
解决方案
Assuming your button is inside of a form, clicking it is probably submitting that form in addition to firing the ajax request.
What you want to do is prevent the default action of clicking the button, which is submitting the form.
Change the function()
parameter to function(event)
, then add an event.preventDefault()
call:
$("#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();
});
相关推荐
最新文章