【问题标题】:How to show loading icon on sweetalert如何在 sweetalert 上显示加载图标
【发布时间】:2021-05-08 20:03:46
【问题描述】:

如何在 ajax 调用期间显示加载图标或旋转。下面是我的代码

 swal({
       title: "Confirm your transaction",
        html:true,
       showSpinner: true,
       showCancelButton: true,
        confirmButtonColor: "#DD6B55",
       confirmButtonText: "Send",
      closeOnConfirm: false
  },function () {
      $.ajax({
   type: "post",
    url: remoteUrl,
    data: largeParams,
   success: function (data) { }
  }).done(function (data) {
    swal("Thank you for your order", data, "success");
  }).error(function (data) {
  swal("Oops", "We couldn't connect to the server!", "error");
 });
});

我们将不胜感激。

【问题讨论】:

  • 我从来没有使用过 SweetAlert,但是查看网页 (sweetalert.js.org) 我找不到所有这些方法:html、showSpinner、showCancelButton、confirmButtonColor、confirmButtonText、closeOnConfirm... 你在使用这个插件还是有其他的?
  • 使用承诺https://sweetalert.js.org/guides/#using-promises

标签: jquery ajax sweetalert


【解决方案1】:

这对我来说效果最好。

以前是这样的:

不要再打开另一个甜蜜警报,而是改变甜蜜警报内的内容,否则在甜蜜警报试图改变时会出现难看的闪烁。

谢天谢地,这个issue 已在版本 9.8.2 中得到解决。


既然上一个问题已经解决,我们可以在 ajax 调用中打开新的甜蜜警报模式,而不会出现丑陋的闪光。

您还可以在swal.fire() 周围放置一个setTimeout,以防止模态之间出现丑陋的过渡,如下所示:

// this way when the ajax call completes quickly, the loader will still be shown for a bit
setTimeout(function() {
    swal.fire({
        icon: 'success',
        html: '<h5>Success!</h5>'
    });
}, 500);
// the loader html
var sweet_loader = '<div class="sweet_loader"><svg viewBox="0 0 140 140" width="140" height="140"><g class="outline"><path d="m 70 28 a 1 1 0 0 0 0 84 a 1 1 0 0 0 0 -84" stroke="rgba(0,0,0,0.1)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></g><g class="circle"><path d="m 70 28 a 1 1 0 0 0 0 84 a 1 1 0 0 0 0 -84" stroke="#71BBFF" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dashoffset="200" stroke-dasharray="300"></path></g></svg></div>';

$.ajax({
    type: 'POST',
    url:  myurl,
    data: str,
    // here
    beforeSend: function() {
        swal.fire({
            html: '<h5>Loading...</h5>',
            showConfirmButton: false,
            onRender: function() {
                 // there will only ever be one sweet alert open.
                 $('.swal2-content').prepend(sweet_loader);
            }
        });
    },
    success: function(json) {
        try {
            json = JSON.parse(json);
        }
        catch(error) {
            swal.fire({
                icon: 'error',
                html: '<h5>Error!</h5>'
            });
            return false;
        }
        if(json.success) {
            swal.fire({
                icon: 'success',
                html: '<h5>Success!</h5>'
            });
        } else {
            swal.fire({
                icon: 'error',
                html: '<h5>Error!</h5>'
            });
        }
    },
    error: function() {
        swal.fire({
            icon: 'error',
            html: '<h5>Error!</h5>'
        });
        return false;
    }
});

查看此codepen 以获取示例。

显然你也可以使用以下来显示实时进度,但我没有测试过。

xhr: function() {
    var xhr = $.ajaxSettings.xhr();
    xhr.upload.onprogress = function(e) {
        // progressive loader
    };
    return xhr;
},

【讨论】:

  • 这对我尝试做的事情非常有帮助,在我等待 AJAX 调用返回时,将不确定的微调器添加到 Sweet Alert 2 模式。但是,如果您正在阅读本文,请首先查看 codepen 代码,因为 CSS 类名称与 Souleste 在此评论中的名称不同。感谢您的帮助!
【解决方案2】:

使用承诺,此代码参考来自网站。

https://sweetalert.js.org/guides/#ajax-requests

swal({
  text: 'Search for a movie. e.g. "La La Land".',
  content: "input",
  button: {
    text: "Search!",
    closeModal: false,
  },
})
.then(name => {
  if (!name) throw null;

  return fetch(`https://itunes.apple.com/search?term=${name}&entity=movie`);
})
.then(results => {
  return results.json();
})
.then(json => {
  const movie = json.results[0];

  if (!movie) {
    return swal("No movie was found!");
  }

  const name = movie.trackName;
  const imageURL = movie.artworkUrl100;

  swal({
    title: "Top result:",
    text: name,
    icon: imageURL,
  });
})
.catch(err => {
  if (err) {
    swal("Oh noes!", "The AJAX request failed!", "error");
  } else {
    swal.stopLoading();
    swal.close();
  }
});

【讨论】:

    【解决方案3】:

    使用 last Sweet Alert 的简单示例

    $('#form_button_submit').click(function(){
    
                swal({
                    title:"", 
                    text:"Loading...",
                    icon: "https://www.boasnotas.com/img/loading2.gif",
                    buttons: false,      
                    closeOnClickOutside: false,
                    timer: 3000,
                    //icon: "success"
                });
                
    
            });
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    </head>
    
    
    
    <button type="submit" id="form_button_submit">
            TEST LOAD
    </button>

    【讨论】:

      【解决方案4】:
      swal({
              title: "Are you sure?",
              text: "",
              confirmButtonClass: "show-loading-icon",
              cancelButtonClass: "show-loading-icon-delete",
              confirmButtonText: "Confirm",
              cancelButtonText: "Cancel",
              closeOnConfirm: false,
              showCancelButton: true,
              closeOnCancel: true,
              titleClass: "bluecolor",
          }, function (selection) {
      
              //If confirm click then show loading on confirm button
              if(selection){
                  var initial = $(".show-loading-icon").html();
      
                  // you can add glyphicon or font-awesome icon html codes
                  $(".show-loading-icon").html("Loading...").attr("disabled", "disabled");
      
                  //Do some operation, eg. ajax call, fetch request etc, then show icon again
                  $(".show-loading-icon").html(initial).removeAttr("disabled");
              }
              else{
      
                  //Similary for cancel also....
                          //.....
      
              }
          });
      

      【讨论】:

        【解决方案5】:

        来自GitHub doc:

        swal({
          title: "Ajax request example",
          text: "Submit to run ajax request",
          type: "info",
          showCancelButton: true,
          closeOnConfirm: false,
          showLoaderOnConfirm: true
        }, function () {
          setTimeout(function () {
            swal("Ajax request finished!");
          }, 2000);
        });

        我已经尝试过了,效果很好,只需将 setTimeout 函数替换为您的 ajax 请求即可。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-19
          • 1970-01-01
          • 1970-01-01
          • 2015-04-18
          • 1970-01-01
          相关资源
          最近更新 更多