如何在ajax完成的函数中检索函数变量

时间:2019-06-18 09:19:00

标签: javascript jquery ajax

我有这个js函数:

$('.editable').change(function () {
    event.preventDefault();
    var el_text = this.lastElementChild;
    var action = this.action;
    var method = this.method;
    var data = $(this).serialize();

    $.ajax({
        url: action,
        type: method,
        data: data,
    }).done(function (resp) {

        // alert('has changed!');
    });
});

如何在 done()中检索el_text,这里似乎是未定义的?

3 个答案:

答案 0 :(得分:2)

您可以这样做,因为已完成回调的范围    函数在自己的范围内考虑此问题,以便获取该变量    您可以简单地在ajax之外的

变量中引用此变量
var objectElement = this;

然后完成回调后,您可以像这样调用它。

$.ajax({
       url: action,
       type: method,
       data: data,
}).done(function (resp) {
     $(objectElement).lastElementChild;     
});

答案 1 :(得分:0)

$('.editable').change(function () {
    event.preventDefault();
    var el_text = this.lastElementChild;
    var action = this.action;
    var method = this.method;
    var data = $(this).serialize();

    // $.ajax({
    //     url: action,
    //     type: method,
    //     data: data,
    // }).done(function (resp) {
    //     // when this is called, el text could be something else as the change event could fire multiple times by differnt element.
    // });

    (function(el_text){
        // now el_text in here is locked in this function scope, 
        // won't be affected by the parent scope
        $.ajax({ 
            url: action,
            type: method,
            data: data,
        }).done(function (resp) {
            // now you can do something with el_text here
        });
    })(el_text);
});

检查以下内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Creating_closures_in_loops_A_common_mistake

答案 2 :(得分:-1)

将var el_text设为公共变量,或将var el_text的数据发送到服务器,然后使用resp重新发送回去

var el_text = "";
$('.editable').change(function () {
    event.preventDefault();
    el_text = this.lastElementChild;
    var action = this.action;
    var method = this.method;
    var data = $(this).serialize();

    $.ajax({
        url: action,
        type: method,
        data: data,
    }).done(function (resp) {

        // alert('has changed!');
    });
});