Ajax jquery success scope

后端 未结 3 1316
执笔经年
执笔经年 2020-11-27 07:02

I have this ajax call to a doop.php.

    function doop(){
        var old = $(this).siblings(\'.old\').html();
        var new = $(this).siblin         


        
相关标签:
3条回答
  • 2020-11-27 07:37

    You should use the context setting as in 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" will be transfer to the success scope and will act as expected.

    0 讨论(0)
  • 2020-11-27 07:40

    this is bound to the object to which the executing function was applied. That could be some AJAX response object, or the global object (window), or something else (depending on the implementation of $.ajax.

    Do I need to capture $(this) into a variable before entering the $.ajax call, and then pass it as a parameter to the $.ajax call? or do I need to pass it to the anonymous success function? If that's going to solve the problem, where do I pass it to the $.ajax?

    You do indeed need a way to capture the value of this before defining the success function. Creating a closure is the way to do this. You need to define a separate variable (e.g. 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;
    }
    

    The success function will retain the value of self when invoked, and should behave as you expected.

    0 讨论(0)
  • 2020-11-27 07:41

    First of all new is a reserved word. You need to rename that variable.

    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);
            }
        }
    })
    

    This is called a closure.

    0 讨论(0)
提交回复
热议问题