首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SweetAlert2和promises

SweetAlert2和promises
EN

Stack Overflow用户
提问于 2017-11-19 02:07:07
回答 1查看 13.6K关注 0票数 2

我正在尝试使用SweetAlert2,但在出现问题时无法显示错误消息。此外,当用户按下" cancel“按钮时,控制台会显示错误: Uncaught (in promise) cancel。

简而言之,我的网站上有一个按钮。如果用户按下该按钮,将出现一个确认对话框(使用SweetAlert2)。下面是我的代码:

代码语言:javascript
复制
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似乎以某种方式捕获了错误,并将其显示在相同的确认框中。此外,cancel按钮也有问题:如果用户取消,控制台将显示前面提到的错误。

SweetAlert2使用promises,我仍然在学习如何正确使用它们,所以可能有一些地方我做错了。

有什么需要帮忙的吗?

提前感谢

EN

回答 1

Stack Overflow用户

发布于 2018-01-18 04:20:40

我刚刚第一次在SWAL2中摆弄完了promises,并因此而在改进我的web应用程序的UX部分方面取得了一些重大进展。我经常使用SWAL2模式,我发现promises在SWAL模式中获取用户输入并验证输入时效果最好。

我使用的是JQuery 3.2.1和PHP5.6版本

这是尝试做我正在做的事情的第一种方法,所以请不要假设它将完全适合您的项目。我还在做一些测试,所以请记住这一点。

我的总体目标是让用户在第一次登录到他们的个人资料(和/或他们在必要的数据库值中有空字段)后,输入我需要的其他信息。

下面是我在宏观层面上使用Promises和Ajax所做的基础工作:

代码语言:javascript
复制
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);

这些模态中的每一个都有不同的输入,我需要验证这些输入,但第一个除外。

代码语言:javascript
复制
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 app”问候之后,我立即开始我的下一个模式。这非常简单。我的代码继续:

代码语言:javascript
复制
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请求,并让模式保持打开状态,直到满足特定条件(所有信息都经过验证,没有错误)。

代码语言:javascript
复制
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);

        }
    }
  });
});
}

然后,一旦满足了该条件,我们就可以使用

代码语言:javascript
复制
}).then(function(result){

然后做我们想做的任何事情,比如添加另一个swal用于图片上传,或者用另一个swal对用户说谢谢。

代码语言:javascript
复制
swal('You\'re all finished!','You now have full access to XYZ web app!','success');

然后,我们确保为我们的第二个模态定义我们的消除函数。在我的例子中,是一个info swal模式:

代码语言:javascript
复制
}, 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);

现在我们就知道了。我知道这是一个相当冗长的解释,但我发现这种用法最适合promises和SWAL2。完成代码后,我们需要定义第一个模式被解除的情况。

代码语言:javascript
复制
}, 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”。然后,JQuery生成一个数组,删除前导零,并为数组中的每个错误输出toastr通知。

我希望这对你使用SWAL2有所帮助。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47369371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档