jQuery 如何添加带有甜蜜警报的 Ajax 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33388492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:57:05  来源:igfitidea点击:

How to Add Ajax Call with sweet alert

jqueryajaxsweetalert

提问by Vikram Anand Bhushan

My Ajax method looks like this

我的 Ajax 方法看起来像这样

$.post(url,{
            ajax_call:"putDonation",
            addresse:addresse,
            phone:phone,
            email:email,
            name:name,
            amount:amount,
            amountinwords:amountinwords
           }).done(function(data){

            console.log(data);

            var arr = [];

            try {
                  var str = "";
                  //convert to json string
                      arr = $.parseJSON(data); //convert to javascript array
                      $.each(arr,function(key,value){
                        str +="<li>"+value+"</li>";
                    });
                       alert(str);
                       $(".alert-danger").show();
                       $("#error").html(str);

              } catch (e) {
                  swal("Jay Gayatri !", 'Donation Sucessful', "success")
                  $("#donation")[0].reset();
              }


           })

I want to show a sweet Alert Warning popup something like this one

我想显示一个类似这样的甜蜜警报警告弹出窗口

   swal({   
                title: "Are you sure ?",   
                text: "You will not be able to recover this imaginary file!",   
                type: "warning",   
                showCancelButton: true,   
                confirmButtonColor: "#DD6B55",   
                confirmButtonText: "Yes, delete it!",   
                closeOnConfirm: false 
              }, 
                function(){   
                  swal("Deleted!", "Your imaginary file has been deleted.", "success"); 
                });

And if they click the cancel it should not do the ajax call , If they select yes then only the call should happen

如果他们单击取消,则不应执行 ajax 调用,如果他们选择是,则只应进行调用

So can any one tell me how can I embed the Ajax method inside Sweet Alertmethods

那么谁能告诉我如何将 Ajax 方法嵌入到Sweet Alert方法中

Thanks

谢谢

回答by Marcel Wasilewski

For a quick example i can show you how i did it on my site. I put the Ajax call inside the sweet alert.

举个简单的例子,我可以向你展示我是如何在我的网站上做到的。我将 Ajax 调用置于甜蜜警报中。

    function deleteorder(orderid) {
        swal({
          title: "Are you sure?", 
          text: "Are you sure that you want to cancel this order?", 
          type: "warning",
          showCancelButton: true,
          closeOnConfirm: false,
          confirmButtonText: "Yes, cancel it!",
          confirmButtonColor: "#ec6c62"
        }, function() {
            $.ajax(
                    {
                        type: "post",
                        url: "/admin/delete_order.php",
                        data: "orderid="+orderid,
                        success: function(data){
                        }
                    }
            )
          .done(function(data) {
            swal("Canceled!", "Your order was successfully canceled!", "success");
            $('#orders-history').load(document.URL +  ' #orders-history');
          })
          .error(function(data) {
            swal("Oops", "We couldn't connect to the server!", "error");
          });
        });
       }

So the ajax call only gets made if you press the confirm button. I hope this can help you to arrange your code the way you need it.

因此,只有按下确认按钮,才会进行 ajax 调用。我希望这可以帮助您按照需要的方式安排代码。

回答by Marosdee Uma

This is my code use in my site.

这是我在我的网站中使用的代码。

            swal({
              title: 'Are you sure?',
              text: "Are you sure that you want to cancel this order?", 
              showCancelButton: true,
              confirmButtonText: 'Confirm',
              cancelButtonText: 'Cancel',
              showLoaderOnConfirm: true,
              preConfirm: function () {
                return new Promise(function (resolve, reject) {
                    $.ajax({
                         success: function(response) {
                              resolve(response)
                         },
                         error: function(a, b, c){
                              reject("error message")
                         }
                    })
                })
              },
              allowOutsideClick: false
            }).then(function (response) {

                swal({
                  title: 'Success',
                  type: 'success',
                  html: '<p>Thank you</p>',
                  showCancelButton: false,
                  confirmButtonColor: '#3085d6',
                  confirmButtonText: 'Close!',
                  allowOutsideClick: false
                }).then(function () {
                    window.location = '/';
                })

            })

In

preConfirm: function () { return new Promise(function (resolve, reject) {}) }

You must call

你必须打电话

resolve(response)

or

或者

reject()

after ajax responses.

在ajax响应之后。

回答by Manoz

Its there in the site reference-

它在站点参考中-

swal({   title: "Ajax request example",   
    text: "Submit to run ajax request",   
    type: "info",   showCancelButton: true,   
    closeOnConfirm: false,   
    showLoaderOnConfirm: true, 
}, 
function(){   
   $.post(url,data,callback)
});

回答by Adarsh

You can do it like this Take a input for sweet alert and send it by ajax request

您可以这样做 为甜蜜警报输入并通过 ajax 请求发送

function change_stock(item_id) {
    swal({
  title: "Edit Stock!!",
  text: "Enter the stock No: you wanded to change",
  type: "input",
  showCancelButton: true,
  closeOnConfirm: false,
  inputPlaceholder: "Write something"
}, function (inputValue) {
  if (inputValue === false) return false;
  if (inputValue === "") {
    swal.showInputError("You need to write something!");
    return false
  }
  setTimeout(function () { 
    $.ajax( 
                    {  
                        type: "POST",
                        url: "edit_stock.php",
                        data: { stock_no : inputValue,itemid:item_id },
                        success: function(){
       swal({ title: "Updated!", text: "Stock No: has Changed", type: "success",}, 
                    function () { location.reload(true); });
                        }
      
      
                    }
            );
          
  }, 2000); 
}

);
            
}