You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SweetAlert2取消按钮异常:点击No触发POST请求而非关闭弹窗

解决SweetAlert中Cancel(No)按钮误发POST请求的问题

嘿,我看你遇到的问题是SweetAlert的"No"按钮现在会触发POST请求,但你只想让它关闭弹窗对吧?这大概率是因为你把请求逻辑不小心放到了所有按钮的回调里,或者没正确区分确认/取消的分支。咱们来修正一下代码:

先看修正后的完整代码(旧版SweetAlert语法)

$('.js-update-details-click').click(function () { 
  var Id = Number($(this).data('result-id')); 
  swal({ 
    title: 'Are you sure you want to ask the User to update their details?', 
    type: 'warning', 
    showCancelButton: true, 
    closeOnConfirm: false, 
    confirmButtonColor: '#3085d6', 
    cancelButtonColor: '#d33', 
    confirmButtonText: 'Yes', 
    cancelButtonText: 'No' // 补全你没写完的取消按钮文本
  }, function(isConfirm) {
    // 只有点击"Yes"(确认按钮)时才执行POST请求
    if (isConfirm) {
      $.post('/your-target-url', { id: Id }, function(response) {
        // 请求成功后的提示,同时关闭弹窗
        swal('Success!', 'User has been requested to update details.', 'success');
      }).fail(function() {
        // 请求失败的提示
        swal('Oops!', 'Failed to send the request.', 'error');
      });
    } else {
      // 点击"No"的话,啥都不用做,弹窗会自动关闭
      // 要是担心关不掉,也可以手动调用swal.close()
      swal.close();
    }
  });
});

如果你用的是新版SweetAlert2,代码可以这么写

$('.js-update-details-click').click(function () { 
  var Id = Number($(this).data('result-id')); 
  Swal.fire({
    title: 'Are you sure you want to ask the User to update their details?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes',
    cancelButtonText: 'No'
  }).then((result) => {
    // 仅当用户点击确认按钮时,才执行POST请求
    if (result.isConfirmed) {
      $.post('/your-target-url', { id: Id })
        .done(function(response) {
          Swal.fire('Success!', 'User has been notified.', 'success');
        })
        .fail(function() {
          Swal.fire('Error!', 'Request failed.', 'error');
        });
    }
    // 点击取消按钮时,弹窗会自动关闭,不需要额外写逻辑
  });
});

关键注意点

  • 核心逻辑:把POST请求的代码严格放在「确认按钮」的回调分支里,取消按钮的分支不要放任何请求相关代码。
  • 旧版SweetAlert通过isConfirm参数判断用户点击的是确认还是取消;新版SweetAlert2则通过result.isConfirmed来判断。
  • 检查一下你有没有在其他地方给弹窗的取消按钮绑定了额外的点击事件,避免意外触发请求。

这样修改后,点击"No"按钮就只会关闭弹窗,不会再发送POST请求啦~

内容的提问来源于stack exchange,提问作者S.zaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:27:53