阿贾克斯jQuery的成功范围 [英] Ajax jquery success scope
问题描述
我有这样的AJAX调用一个 doop.php
。
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;
}
我的问题是, $(本).siblings(旧。)HTML(新);
线路没有做它应该做的。
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
推荐答案
首先新
是的保留字。您需要重命名该变量。
First of all new
is a reserved word. You need to rename that variable.
要回答你的问题,是的,你需要保存这
的成功回调外部的变量,并引用它在你成功的处理程序code:
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);
}
}
})
这就是所谓的<一个href="https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FGuide/Working%5Fwith%5FClosures">closure.
这篇关于阿贾克斯jQuery的成功范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!