[英]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.