1

我使用带有 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 响应?

4

2 回答 2

2

将您的甜蜜警报包装在 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) {
于 2017-09-27T10:18:37.750 回答
1

根据我的经验,是什么让它起作用,记住使用showLoaderOnConfirm: true是在 preconfirm 中进行 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。我希望这对某人有所帮助,因为我花了很长时间才使它工作。

于 2018-05-07T15:15:32.870 回答