访问ajax成功回调中的变量

时间:2014-06-03 20:57:20

标签: javascript jquery ajax

我向ajax提交了以下脚本,提交ID为ajax的任何表单。在成功回调函数中,我想检查是否在我当前的表单上设置了data-after,因为有多个表单具有多个data-after属性。然后console.log()

$('form#ajax').on('submit', function () {
    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {};

    that.find('[name]').each(function (index, value) {
        var that = $(this),
            name = that.attr('name'),
            value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function (response) {
            $('#console p').text(response);
            if (that.attr('data-after').length) {
                // Use data-after to change the text of elements inside current form
                console.log(this);
            }
        }
    });

    return false;
});

that在回调中未定义。

1 个答案:

答案 0 :(得分:0)

您可以通过传递并创建回调闭包来解决此问题。

success: function(that){
     return function (response) {
            $('#console p').text(response);
            if (that.attr('data-after').length) {
                // Use data-after to change the text of elements inside current form
                console.log(this);
            }
        }
      }(that);