我正在尝试使用 SweetAlert2但当出现问题时,我无法显示错误消息。此外,当用户按下“取消”按钮时,控制台会显示错误:未捕获( promise )取消。
简而言之,我的网站上有一个按钮。如果用户按下该按钮,则会出现确认对话框(使用 SweetAlert2)。这是我的代码:
swal({
title: "Are you sure?",
text: "You will not be able to undo this action!",
type: "warning",
showCancelButton: true,
cancelButtonText: 'No, cancel!',
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, do it!",
allowOutsideClick: false
preConfirm: function () {
return axios.put('/api/endpoint')
.then(response => {
console.log('success')
})
.catch(error => {
console.log('failure')
swal({
title: "Something went wrong",
type: "error",
})
});
}
}).then(function (result) {
if (result.value) {
swal('Deleted!', 'Your file has been deleted.', 'success')
} else if (result.dismiss === 'cancel') {
swal('Cancelled', 'Your file is safe :)', 'error')
}
});
如果出现问题,最好显示另一个 SweetAlert2 对话框,上面写着“出现问题”,但事实并非如此,SweetAlert2 似乎以某种方式捕获了错误并将其显示在同一个确认框中。另外,取消按钮也存在问题:如果用户取消,控制台会显示已经提到的错误。
SweetAlert2 使用 Promise,我仍在学习如何正确使用它们,所以也许我做错了一些事情。
请问有什么帮助吗?
提前致谢
最佳答案
我刚刚完成了第一次在 SWAL2 中搞乱 promise ,并因此在改进我的 Web 应用程序的部分用户体验方面取得了一些重大进展。我经常使用 SWAL2 模态,发现在 SWAL 模态中获取用户输入并验证该输入时,Promise 效果最佳。
我使用的是 JQuery 3.2.1 和 PHP 版本 5.6
这是尝试执行我正在做的事情的第一种方法,因此请不要假设它完全适合您的项目。我仍在进行一些测试,因此请记住这一点。
我的总体目标是让用户在第一次登录其个人资料后输入我需要的其余信息(和/或他们有用于必要数据库值的空字段)。
以下是我使用 Promises 和 Ajax 在宏观层面上执行的操作的基础:
swal({...}).then(function(result){ //introduction modal
swal({...}).then(function(result){ //start getting required info
swal({...}).then(function(result){ //get some more required info
}, function (dismiss) {}).catch(swal.noop);
}, function (dismiss) {}).catch(swal.noop);
}, function (dismiss) {}).catch(swal.noop);
除了第一个之外,每个模式都有我需要的不同输入,并且需要验证。
swal({
html:'Welcome to my web app!',
imageUrl: '../path-to-image.png',
imageWidth: 350,
imageAlt: 'My Logo',
animation: false,
showCancelButton: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Complete My Profile',
cancelButtonText: 'Cancel',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
buttonsStyling: false,
focusConfirm: false
}).then(function(result) {
在“欢迎使用 XYZ Web 应用程序”问候语之后,我立即开始下一个模式。这非常简单。如果用户点击他们可以点击的一个绿色按钮,则显示下一个模式;如果用户通过单击关闭模式,则显示另一个模式。我的代码继续:
swal({
title: 'Your Basic Information',
html:
'<div class="form-group"><input type="text" class="form-control" id="FName" name="FName" placeholder="Last Name"></div>'+
'<div class="form-group"><input type="text" class="phone_us form-control" maxlength="14" data-mask="(000) 000-0000" id="userPhone" name="userPhone" placeholder="Phone Number"></div>'+
'<div class="form-group"><div class="input-group"><span class="input-group-addon">$</span><input type="text" class="money form-control" id="avgPrice" name="avgPrice" data-mask="#,##0.00" data-mask-reverse="true" maxlength="5" placeholder="Average Price of your Advice"/></div></div>'+
'<div class="form-group"><textarea class="form-control" name="FInfo" id="FInfo" rows="6" placeholder="Give people a summary of who you are and what kind of great stuff you can do for them."></textarea></div>'+
'<div class="form-group"><label for="FType">Type of kitchen</label><select class="form-control" name="FType" id="FType"><option>--Select--</option><option>Type 1</option><option>Type 2</option><option>Type 3</option><option>Type 4</option><option>Type 5</option></select></div>',
showCancelButton: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Update and Continue',
cancelButtonText: 'Cancel',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
buttonsStyling: false,
focusConfirm: false,
preConfirm: function () {
//Set our Ajax variables in the start of preConfirm
//We could've just made a form element as part of the html, and used a FormData class or form_name.serialize(). The current way is for illustration.
var userPhone = $('#userPhone').val(), FName = $('#FName').val(), avgPrice = $('#avgPrice').val(), FInfo = $('#FInfo').val(), FType = $('#FType').val(), retData = [];
以上变量除retData外均为输入值。 retData 是一个数组,用于存储我从 PHP 收到的错误字符串。然后我可以告诉 JQuery 迭代该数组并将这些错误显示为 toastr 通知。是的,有多种方法可以使用 JSON 来做到这一点。
这是我想要达到的目的。现在,我们可以使用 Promise 在每次用户点击时继续运行我们的 Ajax 请求,并使模式保持打开状态,直到满足特定条件(所有信息都经过验证,并且没有错误)。
return new Promise(function (resolve) {
//Run our actual ajax request inside the promise. Keeps the SWAL2 modal open
$.ajax({
url: prefix+'settings_val_first_modal.php',
type: 'POST',
data: ({userPhone: userPhone, FName: FName, avgPrice: avgPrice, FInfo: FInfo, FType: FType}),
success: function(show) {
retData.push.apply(retData, show.split(","));
//Define the condition that keeps us in the promise.
if(Number(retData[0]) === 0){
//Remove the zero from our error array
retData.shift();
$.each(retData, function(i, val){
//Display each array element as separate toastr notification
toastr.error(retData[i]);
});
} else{
//Define the condition that breaks us out of the promise
resolve(true);
}
}
});
});
}
然后,一旦满足该条件,我们就可以使用
}).then(function(result){
然后做我们想做的任何事情,比如添加另一个 swal 来上传图片,或者用另一个 swal 向用户表示感谢。
swal('You\'re all finished!','You now have full access to XYZ web app!','success');
然后我们确保为第二个模态定义我们的关闭函数。就我而言,信息 swal 模态:
}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
if (dismiss === 'overlay') {
swal(
'Please Finish Your Profile',
'You need to have a completed profile before you can start using XYZ web application',
'info'
);
}
}).catch(swal.noop);
我们就有了。我知道这是一个相当冗长的解释,但我发现这种用法最适合 Promise 和 SWAL2。完成代码后,我们需要定义第一个模态被关闭的情况。
}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
if (dismiss === 'overlay') {
swal(
'Please Contemplate Your Life',
'Don\'t make me have to toggle this modal again! I\'d rather not!',
'info'
);
}
}).catch(swal.noop);
最终,我从一个目标开始,那就是——改善用户体验。 Promise 在这里起作用,因为否则,模式将在每次单击按钮后关闭,并且如果用户做了一些简单的事情(例如不包含带有电子邮件输入或其他内容的@),则必须再次启动整个链。
Promises 让我们在屏幕上保留 SWAL2 模式,直到满足某些条件。条件可以是任何东西,在我的例子中,它是 PHP 中的表单验证将字符串返回给 javascript。如果输入正常,则字符串为“1”。否则,该字符串包含“0”、“无效电话号码”、“帐户已与此电子邮件关联”、“等”等内容。然后,JQuery 创建一个数组,删除前导零,并为数组中的每个错误输出 toastr 通知。
我希望这对您使用 SWAL2 有所帮助。
关于javascript - SweetAlert2 和 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369371/