开发者

how to access the $(this) inside ajax success callback function

It seems that i cannot access $(开发者_高级运维this) inside jquery ajax success function. please see below code.

 $.ajax({
   type: 'post',
   url: '<?php echo site_url('user/accept_deny_friendship_request')?>',
   data: 'action='+$action+'&user_id='+$user_id,
   success: function(response){
     //cannot access $(this) here $(this).parent().remove();
   }
 });


What should $(this) be? If you have a reference to it outside that function, you can just store it into a variable.

$('#someLink').click(function() {
    var $t = $(this);
    $.ajax( ... , function() {
        $t.parent().remove();
    });
}


Check out the context option - works perfectly for me:

$.ajax({
    context: this,
    type: 'post',
    url: '<?php echo site_url('user/accept_deny_friendship_request')?>',
    data: 'action='+$action+'&user_id='+$user_id,
    success: function(response){
       //can access this now!
    }
});


If you want this to be this in the context of your ajax call, you can also use .bind() like the following:

$.ajax({
  url: 'some_url'
  success: function(data) {
    // do something 'this'
  }.bind(this)
})

It binds the value of this inside the success callback to this outside.


Try calling $.proxy, to change the scope of this inside the function:

$.ajax({
    success: $.proxy(function(response) { $(this).parent().bla(); }, $(this));
});


I can't see $(this) referencing anything but easier way would be to give the element a class or id and reference that from jquery:

Instead of:

$(this).parent().remove();

You could do:

$('#element_id').parent().remove();

Note: Here I assume that you are dealing with one element/iteration.


Now, you can simply achieve it using ES6 arrow function. You can convert the anonymous function to arrow function expression as below:

 $.ajax({
   ..,
   success: (response) => {
     // access this outside of this function scope by using `this`
   }
 });

Make sure to use transpiler such as babel to provide support for older browsers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜