如何在sweetalert上显示加载图标

时间:2017-09-23 06:10:25

标签: jquery ajax sweetalert

如何在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");
 });
});

答案将不胜感激。

6 个答案:

答案 0 :(得分:5)

这对我来说效果最好。

以前是这种情况:

与其打开另一个甜蜜警报,不如更改甜蜜警报中的内容,否则当该甜蜜警报试图更改时,将出现难看的闪光。

感谢issue在9.8.2版中已解决。


现在,先前的问题已解决,我们可以在ajax调用中打开新的甜蜜警报模式,而无需执行该操作。

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

// 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;
},

答案 1 :(得分:1)

使用promises,来自网站的此代码参考。

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();
  }
});

答案 2 :(得分:0)

来自GitHub doc:

&#13;
&#13;
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);
});
&#13;
&#13;
&#13;

我已经尝试过这个并且工作正常,只需用你的ajax请求替换setTimeout函数。

答案 3 :(得分:0)

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....
                    //.....

        }
    });

答案 4 :(得分:0)

这里是我的答案,只需在确认时添加“ closeModal:false”,它将显示正在加载gif ...,因为在我的用例中,确认后我会运行ajax进程。然后它会自动关闭,因为我打电话给另一只小马:)希望它能对某人有所帮助!

PS:使用此版本https://sweetalert.js.org/guides/

$(".btn-accept").click(function(){
        swal({
            ....
            buttons:{
                //here is the magic
                confirm : {text:'Telah Saya Terima',className:'sweet-warning',closeModal:false},
                cancel : 'Belum' 
            }
        }).then((confirmed)=>{
            if(confirmed){
                var update = $.ajax({
                   ...
                });

                update.done(function(data){
                    if(data['status']=='success'){
                        swal("Berhasil","Berhasil mengkonfirmasi bahwa Dokumen telah diterima","success").then((ok)=>{
                            //do anything
                        });
                    }else if(data['status']=='failed'){
                        swal("Gagal",data['msg'],"error");
                    }
                });
            }
        });
    });

答案 5 :(得分:0)

使用最后一个 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>