如何在甜蜜警报中使用AJAX

How to use AJAX in Sweet Alert

我希望用户确认是否要更新他的图像。我知道我不能在 javascript 中使用 sql 和 php 并且我尝试了很多方法,但我无法让它工作,没有显示错误,没有任何反应.此代码甚至无需按下按钮即可更新图像。我不了解 AJAX,所以这将是我的代码及其含义的一个很好的示例。

    <script>
function rmv_foto() {
event.preventDefault();
  swal({
    title: 'Remover foto de perfil?',
    text: "Essa ação não poderá ser desfeita.",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#F54400',
    confirmButtonText: 'Sim, pode remover!'
    }).then((result) => {
      if (result.value) {
        var rmv_foto="<?php
        $delete = "UPDATE esc_usuarios_fotos SET img_local = 'images/user.png' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'"; 
        mysqli_query($conexao, $delete) 
        ?>";
        swal(
          'Foto Removida!',
          'Sua foto de perfil foi removida com sucesso.',
          'success'
        ).then(function() {
          location.href = 'perfil.php';
      });
      }
    })
}
</script>

如何正确使用ajax在用户确认时进行更新?

试试下面的代码片段。使用preConfirm函数,指向内部PHP文件做数据库交互

swal({
     title: 'Remover foto de perfil?',
      showCancelButton: true,
      confirmButtonText: 'Sim, pode remover!',
      showLoaderOnConfirm: true,
      preConfirm: ()=>{
            $.ajax({
                url: 'yourPHPfile.php',
                method: 'POST',
                data:{userID:userVar},
                success: function(resp)
                      {
                        if(resp) return "ok"
                      }
            })

          }

    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

有了一些好的研究,工作起来很有魅力!

    function rmv_foto(){
swal({
     title: 'Remover foto de perfil?',
      showCancelButton: true,
      confirmButtonText: 'Sim, pode remover!',
      cancelButtonText: 'Cancelar',
      text: 'Essa ação não poderá ser desfeita.',
      type: 'warning',
      confirmButtonColor: '#F54400',
      showLoaderOnConfirm: true,
      preConfirm: ()=>{
            $.ajax({
                url: 'rmv.php',
                method: 'POST',
                data:{},
                success: function(resp)
                      {
                        if(resp) return "ok",
                          swal(
                            'Foto Removida!',
                            'Sua foto de perfil foi removida com sucesso.',
                            'success'
                          ).then(function() {
                            location.href = 'perfil.php';
                          });
                      }
            })
          }
    })
};