【问题标题】:Handling AJAX return values in SweetAlert2在 SweetAlert2 中处理 AJAX 返回值
【发布时间】:2017-07-29 12:12:28
【问题描述】:

我使用带有 AJAX 请求的 SweetAlert2 弹出窗口。一旦用户点击提交,我就会执行请求。 然后在 PHP 文件中对提交的数据进行一些验证,并根据结果在 SweetAlert2 中为用户提供反馈作为信息。

这是我的 SweetAlert2 代码:

$('#sweet-ajax').click(function () {
    swal({
        title: "Sure?", 
        text: "Clicking on validated sends the data to our tool.", 
        type: "warning",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "Yes, submit!",
        cancelButtonText: "Cancel",
        showLoaderOnConfirm: true,
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger m-l-10',
        preConfirm: function(givenData){
            return new Promise(function(resolve, reject) {
                setTimeout(function(){
                    //if statment only for test purposes filled with 2==1 
                    if(2 == 1){
                        swal("Oops", "Sorry something strange happend!", "error")
                    }else{
                        resolve()
                    }
                }, 2000)
            })
        },
        allowOutsideClick: false
    }).then(function(givenData){
        $.ajax({
                    type: "post",
                    url: "/assets/php/checkTool.php",
                    data: {registration: "success", amount: ammountInput, email: "test@example.com"},
                })
        swal({
                //only if the response from the AJAX is correct - but how?
                type: 'success',
                title: 'Correct!',
                html: 'All safe! Here is the answer from the tool: ' //need to get the return value of the AJAX request and append it here
            })
    }, function(dismiss) {

          if (dismiss === 'cancel') {
            swal(
              'Cancelled',
              'The action have been cancelled by the user :-)',
              'error'
            )
          }
      })

});

还有checkTool.php 文件:

<?php 
     $registration = $_POST['registration'];
     $ammountInput= $_POST['ammount'];
     $email= $_POST['email'];

     //only some demo things here. Implement it after the SweetAlert2 stuff works properly
     if ($registration == "success"){
         return response(json_encode(array("abc"=>'Success')));

     }else{
         return response(json_encode(array("abc"=>'Error')));

     }
?>

我现在如何确定 SweetAlert2 的 Javascript 代码中的 AJAX 请求的响应是什么?

是否可以在 SweetAlert2 中处理 AJAX 响应?

【问题讨论】:

    标签: ajax sweetalert2


    【解决方案1】:

    将您的甜蜜警报包装在 ajax .done(function(response){}) 函数中

    }).then(function(givenData){
            $.ajax({
                    type: "post",
                    url: "/assets/php/checkTool.php",
                    data: {registration: "success", amount: ammountInput, email: "test@example.com"},
                }).done(function(response) {
                    if(response['abc'] === 'Success') {
                        swal({
                            type: 'success',
                            title: 'Correct!',
                            html: 'All safe! Here is the answer from the tool: ' + response['answer'] 
                        })
                    }
                });
            })
    }, function(dismiss) {
    

    【讨论】:

      【解决方案2】:

      根据我的经验,是什么使它起作用,记住showLoaderOnConfirm: true 的使用是在预确认中进行 ajax 调用,并从 json 响应中获取我需要的元素如下:

      swal({
        title: "Sure?", 
        text: "Clicking on validated sends the data to our tool.", 
        type: "warning"
        showLoaderOnConfirm: true,
        preConfirm: function () {
          return new Promise(function (resolve) {
            $.ajax({
              type: "POST",
              contentType: "application/json; charset=UTF-8",
              data: JSON.stringify(objectToPost),
              url: "/assets/php/checkTool.php",
              dataType: 'json', // in ,my case the absence of this was the cause of failure
            })
            // in case of successfully understood ajax response
              .done(function (myAjaxJsonResponse) {
                console.log(myAjaxJsonResponse);
                swal(
                  "My title!",
                  "My response element is: " + myAjaxJsonResponse.selectedElement,
                  "success"
                );
              })
              .fail(function (erordata) {
                console.log(erordata);
                swal('cancelled!', 'The action have been cancelled by the user :-)', 'error');
              })
      
          })
        },
      })
        .catch(swal.noop)
      

      在我的场景中单击按钮时调用的 swal。我希望这对某人有所帮助,因为我花了很长时间才使它工作。

      【讨论】:

      • 我在 Laravel 7 中使用您的解决方案,但由于 TokenMismatchException,我不得不删除 contentType 和 dataType。
      猜你喜欢
      • 2011-05-08
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多