Ajax jquery 成功范围 [英] Ajax jquery success scope
问题描述
我有这个对 doop.php
的 ajax 调用.
I have this ajax call to a doop.php
.
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);
行没有做它应该做的事情.
My problem is that the $(this).siblings('.old').html(new);
line isn't doing what it's supposed to do.
谢谢..所有有用的评论/答案都会被投票赞成.
thanks.. all helpful comments/answers are voted up.
更新: 问题的一半似乎是范围(感谢帮助我澄清这一点的答案),但另一半是我试图在同步中使用 ajax方式.我创建了一个新帖子
Update: it appears that half of the problem was the scope (thanks for the answers that helped me clarify that), but the other half is that I'm trying to use ajax in a synchronous manner. I've created a new post
推荐答案
首先 new
是 保留字.您需要重命名该变量.
First of all new
is a reserved word. You need to rename that variable.
要回答您的问题,是的,您需要将 this
保存在成功回调之外的变量中,并在您的成功处理程序代码中引用它:
To answer your question, Yes, you need to save this
in a variable outside the success callback, and reference it inside your success handler code:
var that = this;
$.ajax({
// ...
success: function(resp) {
if(resp == 1) {
$(that).siblings('.old').html($new);
}
}
})
这称为关闭.
这篇关于Ajax jquery 成功范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!