使用SweetAlert2 弹层(模态,提示框,过几秒消失......等等)

最近在做一个Asp.net MVC的项目,里面用部分视图页弹层,感觉很不爽,用着别扭。在前后端分离的项目里,我们肯定用封装好的前端UI库了,比如element ui,但是 Asp.net MVC的项目里面集成这个比较困难......
就找了个前端弹层组件 SweetAlert2 点击转到官网
还有一个 SweetAlert 2 全网最详细的使用方法

我自己测试过的例子在下面,功能非常全面,我觉得完全够用了,唯一不好得就是 html 要拼接字符串......

// 定义表单提交函数
function submitForm(formData) {
  // 使用 AJAX 将表单数据发送到控制器
  $.ajax({
    url: '/SampleController/SubmitForm',
    type: 'POST',
    data: JSON.stringify(formData), // 将对象转换为 JSON 字符串
    contentType: 'application/json', // 设置请求的内容类型为 JSON
    success: function(response) {
      Swal.fire({
        title: '表单提交成功',
        text: response.message,
        icon: 'success',
        confirmButtonText: '确定', // 确定按钮文本
        showConfirmButton: false, // 不显示确定按钮
        timer: 2000, // 定时器,2秒后自动关闭对话框
        onClose: function() {
          // 对话框关闭后的回调函数
          // 可以在这里执行其他操作
        }
      });
    },
    error: function(xhr, status, error) {
      Swal.fire({
        title: '错误',
        text: '表单提交失败',
        icon: 'error',
        confirmButtonText: '确定' // 确定按钮文本
      });
    }
  });
}

// 当按钮被点击时,打开 SweetAlert2 对话框
document.getElementById('openDialogButton').addEventListener('click', function() {
  const fixedWidth = '80px'; // 定义固定宽度

  const htmlContent = `
    <div style="display: flex; align-items: center;">
      <label for="input1" style="width: ${fixedWidth};">内容1:</label>
      <input type="text" id="input1" name="input1" class="swal2-input">
    </div>
    <div style="display: flex; align-items: center;">
      <label for="input2" style="width: ${fixedWidth};">内容2:</label>
      <input type="text" id="input2" name="input2" class="swal2-input">
    </div>
  `;

  Swal.fire({
    title: '填写内容',
    html: htmlContent,
    customClass: {
      container: 'my-swal-container' // 添加自定义 CSS 类名
    },
    focusConfirm: false,
    cancelButtonText: '取消', // 取消按钮文本
    showCancelButton: true, // 显示取消按钮
    confirmButtonText: '确定', // 确定按钮文本
    showCloseButton: true, // 显示关闭按钮
    preConfirm: function() {
      const input1Value = Swal.getPopup().querySelector('#input1').value;
      const input2Value = Swal.getPopup().querySelector('#input2').value;

      // 验证用户输入
      if (!input1Value || !input2Value) {
        Swal.showValidationMessage('请填写所有内容');
        return false;
      }

      // 封装表单数据为对象
      const formData = {
        input1: input1Value,
        input2: input2Value
      };

      // 调用表单提交函数
      submitForm(formData);

      // 返回一个 Promise 对象,用于关闭对话框
      return Promise.resolve();
    }
  });
});

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值