首页 > 解决方案 > swal 破坏函数的问题

问题描述

我有 swal 函数工作代码,但是当我不做单击取消时,它会进入我不想的 ajax 调用

$(document).on('click','.addon',function() {
    Swal.fire({
      title: 'Provide Your Email Address',
      html: `<input type="email" name="emailaddress" id="emailaddress">
      `,
      confirmButtonText: 'Yes',
      showCancelButton:true,
      focusConfirm: false,
      allowOutsideClick:false,
      preConfirm: () => {
        const emailaddress = Swal.getPopup().querySelector('#emailaddress').value;
        if (!emailIsValid(emailaddress)) {
          Swal.showValidationMessage(`Please enter correct Email`)
        }
        return { emailaddress: emailaddress }
      },
      didDestroy: () => {
        $(this).prop('checked',false);
        return; - if i cancel, it should just quit and not go into tthen, 
      }
    }).then((result) => {
        var data = 'emailaddress=' + Swal.getPopup().querySelector('#emailaddress').value
        $.ajax({
          url: 'submission.cfm',
          data: data,
          type: 'POST',
          success: function(data) {
              var sdata = jQuery.parseJSON(data);
              if($.trim(sdata.status) == 1) {
                  swal.fire({
                      title:"Cool",
                      text: sdata.message,
                      type:"success",
                      confirmButtonText: 'OK'
                  }).then(() => {
                      window.location.reload();
                  });
              }else {
                  var err = sdata.message;
                  swal.fire("Oops...", err, "error");
              }
          }
      });
    })
  });

上面的代码有效,但是当我点击取消时,它仍然会进入 ajax,但我不希望它去那里,我错过了什么吗

标签: javascriptjquerysweetalert2

解决方案


https://sweetalert2.github.io/#showCancelButton似乎记录了您需要的内容:

当用户解除警报时,Swal.fire() 返回的 Promise 将使用对象 { isDismissed: true, dismiss: reason } 解决,记录其被解除的原因:...

所以看来你需要在解析器(then)中处理它:

}).then((result) => {
   if (result.isDismissed) {
     return;
   } else {
       var data = 'emailaddress=' + Swal.getPopup().querySelector('#emailaddress').value
       $.ajax({ ...
   }

推荐阅读