Jquery AJAX call: $(this) does not work after succ

2019-01-26 19:52发布

问题:

I am wondering why $(this) does not work after a jQuery ajax call.

My code is like this.

$('.agree').live("click", function(){  // use live for binding of ajax results
      var id=($(this).attr('comment_id'));
      $.ajax({
        type: "POST",
        url: "includes/ajax.php?request=agree&id="+id,
        success: function(response) {
            $(this).append('hihi');
        }
      });
      return false;
    });

Why doesnt the $(this) work in this case after ajax call? It would work if I use it before the ajax but no effect after.

回答1:

In a jQuery ajax callback, "this" is a reference to the options used in the ajax request. It's not a reference to a DOM element.

You need to capture the "outer" $(this) first:

$('.agree').live("click", function(){  // use live for binding of ajax results
      var id=($(this).attr('comment_id'));
      var $this = $(this);
      $.ajax({
        type: "POST",
        url: "includes/ajax.php?request=agree&id="+id,
        success: function(response) {
                $this.append('hihi');
        }
      });
      return false;
    });


标签: jquery ajax this