我使用sweetalert来确认用户删除行,确认代码是
$('.delete').click(function(){
var formClass = $(this).attr('id');
$("form."+ formClass).submit(function( event ){
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
}, function() {
form.submit();
});
} else {
swal("Cansel", "Not deleted :)", "error");
}
});
});
});
和此代码使用pjax在laravel中有一个ajax请求
$(document).on('pjax:send', function() {
$('#loading').show();
$("#pjax-container").css({"opacity": "0.3"});
})
$(document).on('pjax:complete', function() {
$('#loading').hide();
$("#pjax-container").css({"opacity": "1"});
})
$(document).on('submit', 'form[form-pjax]', function(event) {
$.pjax.submit(event, '#pjax-container')
});
html表单是:
<form action="{{ route('admin.comments.destroy',[$comment->id]) }}" class="inline-div comment-{{ $comment->id }}" method="post" form-pjax>
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type="submit" class="btn btn-sm btn-danger btn-opt delete" id="comment-{{ $comment->id }}"><span class="glyphicon glyphicon-trash"></span></button>
通过此代码我没有ajax请求。
而不是&#34; form.submit();&#34;怎么写?
答案 0 :(得分:1)
从我所看到的,你根本不需要使用pjax。您只需使用ajax请求即可异步删除数据库中的记录。以下是我将如何做到这一点:
在下面的代码中,当用户点击删除链接时,将向他显示警报。如果他确认删除操作,则将调用函数deleteFromDB
,该函数负责向服务器发送ajax请求。
$('.delete').click(function(){
var formClass = $(this).attr('id');
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
deleteFromDB(formClass);
} else {
swal("Cancel", "Not deleted", "error");
}
});
});
上述功能定义如下:
function deleteFromDB(formClass) {
var url = "http://example.com/delete/this/record";
var form = $("form."+ formClass);
var formData = new FormData();
form.find("input[name]").each(function(index, input) {
formData.append(input.name, input.value);
});
$.post(url, formData).done(function(data) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
});
});
}
它找到具有name属性的所有输入,并将每个输入附加到FormData
对象。然后将ajax后请求发送到服务器,当请求完成时,会显示另一个显示删除成功的警报。
注意这里不要在删除记录之前显示成功提醒(正如您在上面的代码中所做的那样),因为如果在请求期间出现问题,即记录不能由于某种原因删除,您将能够向用户显示该错误。