处理SweetAlert2中的AJAX返回值

时间:2017-07-29 12:12:28

标签: ajax sweetalert2

我使用带有AJAX请求的SweetAlert2 Popup。一旦用户点击提交,我就执行请求。 在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响应?

2 个答案:

答案 0 :(得分:2)

将您的甜蜜警报包含在ajax .done(功能(响应){})功能

}).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) {

答案 1 :(得分:0)

根据我的经验,使它工作的是什么,请记住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。我希望这对某人有所帮助,因为我花了很长时间才能使它工作。