簡體   English   中英

Ajax jquery成功范圍

[英]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;
}

“這個”將轉移到成功范圍,並將按預期行事。

首先, new保留字 您需要重命名該變量。

要回答你的問題,是的,你需要保存this在成功回調外的變量,並引用它的成功處理程序代碼中:

var that = this;
$.ajax({
    // ...
    success: function(resp) {
        if(resp == 1) {
            $(that).siblings('.old').html($new);
        }
    }
})

這稱為閉包

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM