【问题标题】:how to access the $(this) inside ajax success callback function如何在ajax成功回调函数中访问$(this)
【发布时间】:2010-04-15 08:38:28
【问题描述】:

似乎我无法在 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();
   }
 });

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

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

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

    【讨论】:

    • 如果无法添加 var 怎么办,因为它被包装在一个函数中,例如:$('.fileupload').fileupload({ dataType: 'json', start: {} ... etc
    • 所以应该是$('.fileupload')?如果是,那么:var $t = $('.fileupload').fileupload(...)
    【解决方案2】:

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

    $.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!
        }
    });
    

    【讨论】:

    • 我同意根据文档,这是正确的选择。根据我的经验,在使用 $.post 而不是 $.ajax 时,我无法使用上下文解决方案。它产生一个错误:“未捕获的类型错误:非法调用”。我正在运行 jQuery v1.11.3 并了解调用错误与被调用的原型函数有关,但即使在找到爆炸的行之后也无法修复它。这似乎是 $.post 和 $.ajax 之间的另一个区别。在特定情况下,使用定义为对函数具有作用域的变量是可行的解决方案。
    【解决方案3】:

    如果您希望 this 在您的 ajax 调用上下文中成为 this,您也可以使用 .bind(),如下所示:

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

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

    【讨论】:

    • 这是唯一对我有用的东西。谢谢。
    【解决方案4】:

    尝试调用$.proxy,改变函数内部this的作用域:

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

    【讨论】:

      【解决方案5】:

      我看不到 $(this) 引用任何东西,但更简单的方法是给元素一个类或 id 并从 jquery 引用它:

      代替:

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

      你可以这样做:

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

      注意:这里我假设您正在处理一个元素/迭代。

      【讨论】:

      • 我没有包含 $(this) 引用的代码。但它会像下面的东西 $('#element_id').click(function(){$.ajax({...})});
      【解决方案6】:

      现在,您可以使用ES6 arrow function 轻松实现它。您可以将匿名函数转换为箭头函数表达式,如下所示:

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

      确保使用诸如 babel 之类的转译器来为旧版浏览器提供支持。

      【讨论】:

        猜你喜欢
        • 2016-09-21
        • 1970-01-01
        • 2016-07-20
        • 1970-01-01
        • 2017-03-14
        • 1970-01-01
        • 1970-01-01
        • 2011-06-26
        • 1970-01-01
        相关资源
        最近更新 更多