如何在AJAX成功中访问$(this)里面的甜蜜警报

时间:2016-08-11 22:35:04

标签: javascript jquery ajax sweetalert

我想删除clicked元素的父元素。我首先使用甜蜜的警报来获取警报,在我调用AJAX函数之后,我想获得成功函数中的元素:

这是我的功能:

 function removeImage(id) {  
        var element = $(this).closest('.dropzone');

    swal({   
      title:"Delete",   
      text: "delete",  
      type: "warning",   
      showCancelButton: true,   
      confirmButtonColor: "#DD6B55",   
      confirmButtonText: "Yes !",   
      cancelButtonText: "No, cancel",   
      closeOnConfirm: false,   closeOnCancel: false 
    }, function(isConfirm){
      if (isConfirm) {
        $.ajax({
          type: "POST", 
          data: {id: id},
          url:'ajax/deleteimage.php',
          success : function(data){ 
            if(data == 'ok'){
                    swal({   
                title:"Delete",   
                text: "delete",  
                type: "success",    
                confirmButtonColor: "#AEDEF4",
                confirmButtonText: "Ok",   
                closeOnConfirm: true,   
              }, function(isConfirm){
                    $.when($('.dropzone').find("#"+id).parent().fadeOut())
                                       .done(function() {
                          $('.dropzone').find("#"+id).parent().remove();
                      });
                      var n_div = $('.dz-image-preview').length-1;
                          if (n_div === 0) {
                             $('.dz-message').css("opacity",'1');
                          }
              });
            }else{
              swal("Error, try again", "", "error");  
            }  
               }
        }); // end ajax call 

      } else {     
        swal("Cancel", "", "error");   
      } 
    }); 


  }

我无法使用变量元素更改成功函数中的$('.dropzone')

1 个答案:

答案 0 :(得分:1)

我在jQuery中遇到了同样的问题。主要问题是ajax无法在swal中直接访问此上下文。所以,我们需要将此上下文传递给ajax。首先,我们将此上下文存储在变量中,然后在ajax中分配该上下文。

$(".delete_category").click(function () {
    var call_url = $(this).val();
    var this_context = $(this);
    swal({
        title: "Are you sure?",
        text: "Your may not be able to recover!",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    },
        function () {
            $.ajax({
                context: this_context,
                method: "POST",
                url: call_url,
                success: function (response) {
                    if (response == "success") {
                        swal("Deleted!", "Record deleted successfully.", "success");
                        $(this).closest('.delete_row').hide();
                    } else {
                        swal("Error!", response, "error");
                    }
                }
            });

        }
    );
});