问题描述
我是 Javascript 新手 - 实际上是第一次编码.我正在尝试使用 SweetAlert 做一个带有删除确认的按钮.当我按下带有 onclick="confirmDelete()"
的按钮时,没有任何反应.这段代码可能只是螃蟹,但在这里:
I'm new at Javascript - coding it actually for the first time.I'm trying to do a button with delete confirmation with SweetAlert. Nothing happens when I press the button with onclick="confirmDelete()"
. This code may be just crab, but here it is:
<script type="text/javascript">
function confirmDelete() {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
)},
$.ajax({
url: "scriptDelete.php",
type: "POST",
data: {id: 5},
dataType: "html",
success: function () {
swal("Done!","It was succesfully deleted!","success");
}
});
}
</script>
<a href="#" onclick="confirmDelete()">Delete</a>
如果删除失败,我可以添加任何提醒吗?
Can I add any alert if deleting fails?
推荐答案
如果我正确理解您的问题,您是在询问如何处理 ajax 请求中的错误情况.Ajax 设置有一个错误属性,它可以像这样使用
If I understand your question correctly, you are asking how to handle error condition in ajax request. Ajax settings has an error attribute and it can be used like this
$.ajax({
.... other settings you already have
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
此外,您以错误的方式调用 swal.Swal 有一个这样的回调
Also, you are invoking swal in a wrong way. Swal has a callback like this
swal({settings}, function(isConfirm){});
整体代码看起来像这样
function confirmDelete() {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function (isConfirm) {
if (!isConfirm) return;
$.ajax({
url: "scriptDelete.php",
type: "POST",
data: {
id: 5
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}
这是一个演示 http://jsfiddle.net/dhirajbodicherla/xe096w10/33/
Here is a demo http://jsfiddle.net/dhirajbodicherla/xe096w10/33/
这篇关于SweetAlert 确认 Ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!