You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AJAX getJSON请求成功后按钮UI无法更新问题求助

解决收藏按钮点击后UI不更新的问题

核心问题很明确:AJAX回调里的this指向不对——在$.getJSON().done()的回调函数里,this已经不再指向你点击的那个按钮元素了,所以你修改$(this)的属性和内容自然不会生效。下面是具体的修复方案和优化建议:

1. 修复核心的this指向问题

在按钮点击事件的一开始,把当前按钮的DOM元素引用存到一个变量里,这样在AJAX回调里就能直接用这个变量操作按钮了:

$(document).ready(function () {
    $('.button').click(function (e) {
        e.preventDefault();
        // 提前保存当前按钮的引用,避免回调里this指向混乱
        const $currentBtn = $(this);
        $.getJSON('favs.php', {
            user_id: $currentBtn.attr('data-user'),
            director_id: $currentBtn.attr('data-post'),
            method: $currentBtn.attr('method')
        })
        .done(function (json) {
            switch (json.feedback) {
                case 'Like' :
                    $currentBtn.attr('method', 'Unlike');
                    $currentBtn.html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn');
                    break;
                case 'Unlike' :
                    $currentBtn.html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button');
                    $currentBtn.attr('method', 'Like');
                    break;
                case 'Fail' :
                    alert('The Favorite setting could not be changed.');
                    break;
            }
        })
        .fail(function (jqXHR, textStatus, error) {
            alert("Error Changing Favorite: " + error);
        });
    });
});

2. 额外的代码优化建议

除了修复核心问题,还有几个小细节能让你的代码更健壮:

  • 重构PHP的checkFavorite函数,让它返回字符串而不是直接echo,代码结构更清晰:
function checkFavorite($mbid, $pid, $conn) {
    $stmt = $conn->prepare("SELECT * FROM favorite WHERE memberID=:mid AND id=:id");
    $stmt->execute(array(':mid' => $mbid, ':id' => $pid));
    $count = $stmt->rowCount();
    if ($count == 0) {
        return "<div class='button btn btn-block btn-outline-danger' method='Like' data-user=" . $mbid . " data-post=" . $pid . "> Add<i class='mi mi_sml ml-2' id='favorite-icon-{$pid}'>favorite_border</i></div>";
    } else {
        return "<div class='button btn btn-block btn-outline-danger' method='Unlike' data-user=" . $mbid . " data-post=" . $pid . ">Remove<i class='mi mi_sml ml-2' id='favorite-icon-{$pid}'>favorite</i></div>";
    }
}

// 调用时输出
echo "Favorite? : " . checkFavorite($mbid, $pid, $conn) . "";
  • 避免重复ID:原来的<i>标签用$pid作为ID,多帖子场景下会出现重复ID问题,改成favorite-icon-{$pid}这种唯一标识更规范;
  • 保持PDO预处理的好习惯:你已经用了参数绑定防止SQL注入,这一点做得很好,继续保持。

为什么原来的代码不生效?

当进入AJAX的done回调时,this的上下文已经变成了AJAX请求的jqXHR对象,不再是你点击的按钮元素。提前把按钮引用存在变量里,就能绕开这个指向问题,正确操作目标元素。

内容的提问来源于stack exchange,提问作者sanoj lawrence

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:02:50