【问题标题】:AJAX call with error catching in SweetAlert2在 SweetAlert2 中捕获错误的 AJAX 调用
【发布时间】:2018-06-26 13:58:40
【问题描述】:

我现在摸不着头脑,我无法让 SweetAlert2 进行 AJAX 调用,如果成功则返回“Success”,如果出现问题,我无法在同一个框中显示错误,让用户可以重试。

到目前为止,我的实现如下。问题是它在框中显示错误,但同时将其关闭:

swal({
  title: 'Submit?',
  text: 'Are those informations correct?',
  type: 'question',
  showCancelButton: true,
  confirmButtonText: 'Absolutely',
  cancelButtonText: 'Not sure',
  showLoaderOnConfirm: true,
  preConfirm: function() {
    return new Promise(function(resolve,reject) {
      $.ajax({
        url: '*****', // Invalid URL on purpose
        type: 'POST',
        data: {test: true}
      })
      .done(function(data) {
        resolve(data)
      })
      .fail(function() {
        reject()
      });

    })
  },
  allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
  if (result.value) {
    swal({
      title: `Success`,
      text: result.value
    })
  }
}).catch((result) => {
  swal.showValidationError('POST failed. Please try again.');
})

documentation 中,我找不到带有showValidationError 的AJAX 调用。我找到的最接近的是 fetch() 调用,但据我所知,这些仅用于 GET。

我也尝试过类似:return truereturn falsethrow new Error、promise 中的 promises,但这都是反复试验,所以我来到了这里。

我也做了个小提琴:https://jsfiddle.net/xpvt214o/306267/

提前感谢您的任何帮助和/或建议。

【问题讨论】:

    标签: javascript jquery ajax sweetalert2


    【解决方案1】:

    又过了一天,我想通了。我必须 .then.catch $.ajax 并附上 swal.showValidationError 才能工作。

    在出现 AJAX 错误时,它现在会在同一个框中显示以下内容(用户可以随意尝试多次):

    成功后:

    swal({
      title: 'Submit?',
      text: 'Are those informations correct?',
      type: 'question',
      showCancelButton: true,
      confirmButtonText: 'Absolutely',
      cancelButtonText: 'Not sure',
      showLoaderOnConfirm: true,
      preConfirm: () => {
        return $.ajax({
          url: '***',
          type: 'POST',
          data: 'test'
        })
        .then(response => {
          return response
        })
        .catch(error => {
          //console.log(error); // Nice to view which properties 'error' has
          swal.showValidationError(
            `An error ocurred: ${error.status}`
          )
        })
    
      },
      allowOutsideClick: () => !swal.isLoading()
    }).then((result) => {
      if (result.value) {
        swal({
          type: 'success',
          title: 'Success',
          text: result.value
        })
      }
    })
    

    小提琴:https://jsfiddle.net/z3kfhsj8/6/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多