[英]Ajax jquery success scope
我有一个doop.php
ajax调用。
function doop(){
var old = $(this).siblings('.old').html();
var new = $(this).siblings('.new').val();
$.ajax({
url: 'doop.php',
type: 'POST',
data: 'before=' + old + '&after=' + new,
success: function(resp) {
if(resp == 1) {
$(this).siblings('.old').html(new);
}
}
});
return false;
}
我的问题是$(this).siblings('.old').html(new);
line没有做它应该做的事情。
谢谢..所有有用的评论/答案都被投了票。
更新:似乎问题的一半是范围(感谢帮助我澄清的答案),但另一半是我试图以同步方式使用ajax。 我创建了一个新帖子
您应该使用http://api.jquery.com/jQuery.ajax/中的上下文设置
function doop(){
var old = $(this).siblings('.old').html();
var newValue = $(this).siblings('.new').val();
$.ajax({
url: 'doop.php',
type: 'POST',
context: this,
data: 'before=' + old + '&after=' + newValue,
success: function(resp) {
if(resp == 1) {
$(this).siblings('.old').html(newValue);
}
}
});
return false;
}
“这个”将转移到成功范围,并将按预期行事。
this
绑定到应用执行函数的对象。 这可能是一些AJAX响应对象,或全局对象( window
),或其他东西(取决于$.ajax
的实现。
在进入$ .ajax调用之前,是否需要将$(this)捕获到变量中,然后将其作为参数传递给$ .ajax调用? 或者我是否需要将其传递给匿名成功函数? 如果这将解决问题,我将在哪里将其传递给$ .ajax?
你确实需要一种方法来捕捉值this
定义之前success
功能。 创建闭包是实现此目的的方法。 您需要定义一个单独的变量(例如self
):
function doop() {
var old = $(this).siblings('.old').html();
var new = $(this).siblings('.new').val();
var self = this;
$.ajax({
url: 'doop.php',
type: 'POST',
data: 'before=' + old + '&after=' + new,
success: function(resp) {
if(resp == 1) {
$(self).siblings('.old').html(new);
}
}
});
return false;
}
success
函数在调用时将保留self
的值,并且应该按预期运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.