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

Bootstrap模态框结合AJAX无法填充表单数据问题求助

问题:Bootstrap模态框结合AJAX获取数据后无法填充表单

我用Bootstrap模态框配合AJAX实现数据更新功能时遇到异常:通过console.log()能正常获取返回数据,但无法将数据填充到模态框内的表单控件中。以下是我的jQuery代码与模态框代码,期望解决表单填充失败的问题。

jQuery代码

$(".update-category").click(function (event) {
  const id = $(this).data("id");
  const url = `/Category/GetId?id=${id}`;
  $(".modal-update-category").modal('show');

  $(".modal-update-category").on("shown.bs.modal", function (e) {
    $.ajax({
      method: 'GET',
      url: url,
      contentType: 'application/json',
      success: function (response) {
        $("#categoryName").val(response.categoryName);
        $("#categoryDesc").val(response.description);
      },
      error: function (xhr, status, error) {
        console.log(`Error: ${error}`);
      }
    });
  });
});

模态框代码

<div class="modal fade modal-update-category" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div id="liveAlertPlaceholder"></div>
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Insert Category</h5>
            </div>
            <form>
                <div class="modal-body">
                    <div class="form-group row">
                        <div class="col text-center">
                            <label class="col col-form-label fs-6">Category Name</label>
                        </div>
                        <div class="col modal-input ">
                            <input type="text" class="form-control" id="categoryName">
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col text-center">
                            <label class="col col-form-label fs-6">Description</label>
                        </div>
                        <div class="col modal-input">
                            <textarea type="text" class="form-control" id="categoryDesc" style="height: 100px"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary text-light btn-category-submit">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

问题分析与解决方法

1. 解决事件重复绑定问题

每次点击.update-category按钮时,都会给模态框新增一个shown.bs.modal事件监听,多次点击后会触发重复请求,导致DOM操作冲突。修改方式:绑定事件前先解绑旧监听,或者将事件监听移到点击事件外部:

$(".update-category").click(function (event) {
  const id = $(this).data("id");
  const url = `/Category/GetId?id=${id}`;
  const modal = $(".modal-update-category");

  // 解绑旧事件,避免重复触发
  modal.off("shown.bs.modal").on("shown.bs.modal", function (e) {
    $.ajax({
      method: 'GET',
      url: url,
      success: function (response) {
        // 先打印确认返回数据结构
        console.log(response);
        $("#categoryName").val(response.categoryName);
        $("#categoryDesc").val(response.description);
      },
      error: function (xhr, status, error) {
        console.log(`Error: ${error}`);
      }
    });
  });

  modal.modal('show');
});

2. 移除冗余的contentType设置

GET请求没有请求体,设置contentType: 'application/json'属于冗余操作,甚至可能导致解析异常,直接删除即可。

3. 确认DOM选择器唯一性

检查页面中是否存在多个id="categoryName"或id="categoryDesc"的元素。jQuery只会选中第一个匹配元素,若存在重复ID,会导致填充失效,需确保这两个ID全局唯一。

4. 验证返回数据结构

在success回调中打印response,确认返回的JSON对象中categoryName和description字段的大小写、名称与后端返回完全一致,避免因字段名不匹配导致赋值失败。

内容的提问来源于stack exchange,提问作者Adam Fikar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:45:18