我点击删除按钮时运行此代码:
$(document).on('click', '.remove', function (e) {
e.preventDefault();
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "<?php echo Yii::$app->request->baseUrl;?>"+'/todo/deletetask',
data: {id:id},
success: function (data) {
var res = $.parseJSON(data);
if(res != false) {
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function(){
window.location.href = "<?php echo Yii::$app->request->baseUrl;?>/todo/index/";
});
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
控制器动作是:
public function actionDeletetask()
{
if(Yii::$app->request->isAjax)
{
$id = $_POST['id'];
if($id)
{
Todo::find()->where(['todo_id'=>$id])->one()->delete();
}
echo json_encode(TRUE);die;
}
echo json_encode(FALSE);die;
}
Run Code Online (Sandbox Code Playgroud)
但即使我点击甜蜜警报取消按钮,任务也会被删除,这是显而易见的.但我该怎样才能阻止它呢?
就在sweetalert网站的首页上,它显示如果你包含一个取消按钮,你的回调会得到一个参数,说明该动作是否被确认或取消; 从该页面:
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!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}, function(isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
Run Code Online (Sandbox Code Playgroud)
所以接受上面显示的参数,只有删除才真正删除.
您的代码存在的问题是,当您单击按钮时 - 代码会将请求发送todo/deletetask到您的服务器,并且只有在请求完成时(任务被删除),您才会向用户显示确认消息.
相反 - 您应该做的是在用户单击按钮时向用户显示确认消息 - 并且仅当用户确认删除了任务时 - 您需要将todo/deletetask请求发送到服务器.
以下是使用新逻辑修复的代码:
$(document).on('click', '.remove', function (e) {
e.preventDefault();
var id = $(this).data('id');
// Show the user a swal confirmation window
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
// This function will run ONLY if the user clicked "ok"
// Only here we want to send the request to the server!
$.ajax({
type: "POST",
url: "<?php echo Yii::$app->request->baseUrl;?>"+'/todo/deletetask',
data: {id:id},
success: function (data) {
var res = $.parseJSON(data);
if(res != false) {
swal("Task Deleted", "", "success")
}
}
});
},
function() {
// This function will run if the user clicked "cancel"
window.location.href = "<?php echo Yii::$app->request->baseUrl;?>/todo/index/";
}
);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16017 次 |
| 最近记录: |