2017-07-29 216 views
0

我使用带有AJAX请求的SweetAlert2 Popup。一旦用户点击提交,我执行请求。 在PHP文件中,我对提交的数据进行了一些验证,根据结果,我想在SweetAlert2中为用户提供反馈作为信息。处理SweetAlert2中的AJAX返回值

这是我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: "[email protected]"}, 
       }) 
     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响应?

回答

0

包裹AJAX .done(功能(响应){})功能

}).then(function(givenData){ 
     $.ajax({ 
       type: "post", 
       url: "/assets/php/checkTool.php", 
       data: {registration: "success", amount: ammountInput, email: "[email protected]"}, 
      }).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) { 
里面你甜蜜的警报