Jquery 如何在ajax成功回调函数中访问$(this)
似乎我无法在jQueryAjax成功函数中访问$(this)。请参阅下面的代码Jquery 如何在ajax成功回调函数中访问$(this),jquery,ajax,Jquery,Ajax,似乎我无法在jQueryAjax成功函数中访问$(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
$.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();
}
});
$.ajax({
键入:“post”,
url:“”,
数据:'action='+$action+'&user\u id='+$user\u id,
成功:功能(响应){
//无法访问$(this)here$(this.parent().remove();
}
});
我看不到$(这)
引用任何东西,但更简单的方法是给元素一个类或id,并引用来自jquery的:
而不是:
$(this).parent().remove();
你可以做:
$('#element_id').parent().remove();
注意:这里我假设您处理的是一个元素/迭代。应该是什么$(this)
?如果在该函数外部有对它的引用,则可以将其存储到变量中
$('#someLink').click(function() {
var $t = $(this);
$.ajax( ... , function() {
$t.parent().remove();
});
}
尝试调用,以更改函数中此的范围:
$.ajax({
success: $.proxy(function(response) { $(this).parent().bla(); }, $(this));
});
查看上下文选项-非常适合我:
$.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!
}
});
$.ajax({
背景:这,,
键入:“post”,
url:“”,
数据:'action='+$action+'&user\u id='+$user\u id,
成功:功能(响应){
//你现在可以访问这个!
}
});
如果希望在ajax调用的上下文中this
成为this
,也可以使用.bind()
,如下所示:
$.ajax({
url: 'some_url'
success: function(data) {
// do something 'this'
}.bind(this)
})
它将成功回调内部的
this
值绑定到外部的this
。我没有包括$(this)引用的代码。但是它可能是$('#element_id')下面的东西;我同意根据文件,这是正确的选择。根据我的经验,在使用$.post而不是$.ajax时,我无法使用上下文解决方案。它会产生一个错误:“UncaughtTypeError:非法调用”。我正在运行jqueryv1.11.3,并且理解调用错误与被调用的原型函数有关,但是即使在找到发生爆炸的行之后也无法修复它。这似乎是$.post和$.ajax之间的又一个区别。使用定义为在函数上具有作用域的变量是该特定情况下的有效解决方案。如果无法添加变量,因为它被包装在一个函数中,例如:$('.fileupload')。fileupload({dataType:'json',start:{}…etc
,那么它应该是$('.fileupload')
?如果是,那么:var$t=$('.fileupload').fileupload(…)