如何在ajax成功回调函数中访问$(this)

Yal*_*ber 30 ajax jquery

看来我无法在jquery ajax成功函数中访问$(this).请看下面的代码.

 $.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();
            }
        });
Run Code Online (Sandbox Code Playgroud)

nic*_*ckf 54

应该$(this)是什么?如果您在该函数之外引用它,则可以将其存储到变量中.

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


Eni*_*lus 53

查看上下文选项 - 对我来说非常适合:

$.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!
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 这应该是已接受的答案,目前接受的答案似乎是一个黑客 (14认同)

Sun*_*Cho 5

如果你想this成为this你的Ajax调用的情况下,也可以使用.bind()像下面这样:

$.ajax({
  url: 'some_url'
  success: function(data) {
    // do something 'this'
  }.bind(this)
})
Run Code Online (Sandbox Code Playgroud)

它将this成功回调内部的值绑定到this外部。