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

PHP Ajax项目中Ajax成功后禁用按钮并修改按钮文本

问题与解决方案:Ajax成功回调中仅禁用触发请求的动态按钮

问题描述

我正在开发一个PHP Ajax项目,目前Ajax功能运行正常且能获取预期输出,仅需补充实现:在Ajax的success回调函数中,仅对触发请求的那个动态按钮执行禁用操作并修改其文本。

我的Ajax代码

$(document).ready(function () {

  $(document).on("click", "#add_btn", function (e) {
    e.preventDefault();
    var id = $(this).val();
    var cus_id = $('#customer_selection').val();
    if (!cus_id) {
      alert("Please select a customer")

    } else {

      $.ajax({
        url: "add_selection_script.php",
        type: "POST",
        data: {
          id: id,
          cus_id: cus_id
        },
        success: function (data) {
          // here i want to change button text and disable for click button only
            not others because my buttons are dynamic
          prop("disabled", true);
          html("Added");

        }
      });
    }
  });
});

按钮代码

<button type="submit" id="add_btn" value="<? echo $id; ?>">Add to selection</button>

解决方案

核心问题分析

  1. 所有动态按钮共用同一个id="add_btn",但HTML规定ID必须唯一,重复ID会导致选择器无法精准定位单个按钮。
  2. Ajax的success回调中this的指向已不是触发点击的按钮,直接调用prop()和html()会报错,且无法定位目标按钮。

修正步骤

  1. 修改按钮标识为类名:将按钮的id="add_btn"改为class="add_btn",适配多个动态按钮的场景:
<button type="submit" class="add_btn" value="<? echo $id; ?>">Add to selection</button>
  1. 保存触发按钮的引用:在点击事件中,提前用变量保存当前触发请求的按钮,避免回调中this指向变化的问题:
$(document).on("click", ".add_btn", function (e) {
  e.preventDefault();
  var $currentBtn = $(this); // 保存当前按钮引用
  var id = $currentBtn.val();
  var cus_id = $('#customer_selection').val();
  
  // ... 其余逻辑不变
});
  1. 在success回调中操作目标按钮:用之前保存的$currentBtn变量,直接对触发请求的按钮执行禁用和文本修改:
success: function (data) {
  $currentBtn.prop("disabled", true).html("Added");
}

修改后的完整Ajax代码

$(document).ready(function () {

  $(document).on("click", ".add_btn", function (e) {
    e.preventDefault();
    var $currentBtn = $(this);
    var id = $currentBtn.val();
    var cus_id = $('#customer_selection').val();
    
    if (!cus_id) {
      alert("Please select a customer");
    } else {
      $.ajax({
        url: "add_selection_script.php",
        type: "POST",
        data: {
          id: id,
          cus_id: cus_id
        },
        success: function (data) {
          $currentBtn.prop("disabled", true).html("Added");
        }
      });
    }
  });
});

内容的提问来源于stack exchange,提问作者Kashmiri Ammar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:50:24