js和ajax调用删除记录:
$('.delete').click(function (e) {
if (confirm("Are you sure want to delete record?")) {
return true;
}
else {
e.preventDefault();
}
});
$('.type_delete').click(function() {
var csrf_token = $("#csrf_token").val();
var id = $(this).attr('id');
$.ajax({ // create an AJAX call...
data:{
csrfmiddlewaretoken: ('{{csrf_token}}'),
delete:id
},
type:'POST',
url: '/setting/type/', // the file to call
cache:false,
success: function() { // on success..
window.location.href = window.location;
}
});
return false;
});
});
views.py
def types(request):
if request.method == 'POST':
if 'delete' in request.POST:
Types.objects.filter(id=request.POST['delete']).delete()
"""""""""
return render
HTML:
<input type="button" name="delete" value="Delete" id="{{ type.id }}" class="type_delete delete"/>
上面的ajax是从html中获取正确的id并删除那个特定的数据。删除工作正常,我正在使用删除确认对话框,问题是数据被删除即使我按下取消按钮或关闭符号。只有按下确定才会发生。我需要帮助来解决这个问题。
答案 0 :(得分:1)
当您显示确认框时,第二个功能的调用已在进行中。您需要将第二个函数定义为另一个独立函数,然后从第一个函数中调用它。
以下是一个例子:
$('.delete').click(function (e) {
e.preventDefault();
if (confirm("Are you sure want to delete record?")) {
doDelete($(this).attr('id'))
}
});
function doDelete(elemId) {
var csrf_token = $("#csrf_token").val();
var id = elemId;
$.ajax({ // create an AJAX call...
data:{
csrfmiddlewaretoken: ('{{csrf_token}}'),
delete:id
},
type:'POST',
url: '/setting/type/', // the file to call
cache:false,
success: function() { // on success..
window.location.href = window.location;
});
}
答案 1 :(得分:0)
一个事件处理程序中的条件不一定适用于第二个事件处理程序,您必须在一个事件处理程序中将它们全部连接起来:
$('.type_delete').on('click', function (e) {
e.preventDefault();
if (confirm("Are you sure want to delete record?")) {
var csrf_token = $("#csrf_token").val(),
id = this.id;
$.ajax({
data: {
csrfmiddlewaretoken: '{{'+csrf_token+'}}',
delete: id
},
type: 'POST',
url: '/setting/type/',
cache: false
});
}
});