如何在 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

你可以这样做,因为 done 回调的范围 函数在它自己的范围内考虑这一点,以便获得该变量 你可以简单地在 ajax 外部的变量中引用它

var objectElement = this;

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

$.ajax({
       url: action,
       type: method,
       data: data,
}).done(function (resp) {
     $(objectElement).lastElementChild;     
});
$('.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

将 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!');
    });
});

最新更新