Javascript 在适当的范围/上下文中保持jQuery AJAX成功响应

Javascript 在适当的范围/上下文中保持jQuery AJAX成功响应,javascript,php,jquery,ajax,scope,Javascript,Php,Jquery,Ajax,Scope,我有动态生成的内容,每个内容项都包含一个简单的一键表单,用于在收藏夹列表中添加/删除其中一个内容项。我使用jQuery的ajax方法发布表单并获得响应,除了成功回调应用于每个表单中的每个按钮元素,而成功回调应该只应用于单击的按钮之外,其他一切都很好。我已经为此挣扎了几个小时,不知道为什么它不在合适的范围内 以下是我的jQuery: $('form.ajax').on('submit', function(){ var that = $(this), url = that.

我有动态生成的内容,每个内容项都包含一个简单的一键表单,用于在收藏夹列表中添加/删除其中一个内容项。我使用jQuery的ajax方法发布表单并获得响应,除了成功回调应用于每个表单中的每个按钮元素,而成功回调应该只应用于单击的按钮之外,其他一切都很好。我已经为此挣扎了几个小时,不知道为什么它不在合适的范围内

以下是我的jQuery:

$('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) {
            $('button').text(response);
        };
    });

    return false;
});
以下是生成的表单:

if($user->isLoggedIn()) {
    $addFave = NULL;
    $favorites = DB::connectDB()->query("SELECT * FROM ajaxfavourites WHERE user = '{$userid}' AND favid = '{$favid}'");
    $matches = mysqli_num_rows($favorites);
    if ($matches == 0) {
        $addFave = '
            <form action="../app/parsers/faves_addremove.php" method="post" class="ajax">
                <input type="hidden" name="user" value="' . escape($user->data()->id) . '">
                <input type="hidden" name="favid" value="' . ++$nfave . '">
                <button id="addFave" class="btn rb-faucet-button btn-default bg-color-1"><span class="glyphicon glyphicon-star" aria-hidden="true"></span> Add To Faves</button>
            </form>
        ';
    } else {
        $addFave = '
            <form action="../app/parsers/faves_addremove.php" method="post" class="ajax">
                <input type="hidden" name="user" value="' . escape($user->data()->id) . '">
                <input type="hidden" name="favid" value="' . ++$nfave . '">
                <button id="addFave" class="btn rb-faucet-button btn-default bg-color-1"><span class="glyphicon glyphicon-star" aria-hidden="true"></span> Remove From Faves</button>
            </form>
        ';
    }
} else {
    $addFave = '';
}

如果我单击按钮向AjaxFavorites表添加一个项目,我的响应文本“Added”将应用于页面上任何带有“ajax”类的表单中的每个按钮元素。我错过了什么?我认为我已经正确地在范围内了,我尝试过的任何东西似乎都不起作用。

您正在处理成功回调中的所有按钮,
$(“按钮”)
将返回页面上的所有按钮

您应该使用如下内容:

success: function(response) {
    that.find('button').text(response);
}
由于
指的是您正在使用的
表单
,因此应检索表单中的所有
按钮
元素


如果表单中有多个按钮,则应为其提供一个描述性类。i、 e
that.find('button.useThisButton').text(响应)

漂亮。。。一直盯着我的脸。。。非常感谢你!
success: function(response) {
    that.find('button').text(response);
}