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

AJAX请求成功但bootstrap-select无法填充数据的问题排查

问题解决:bootstrap-select通过AJAX填充后显示为空

你现在的问题核心是直接把JSON字符串设置为select的HTML内容,这会让控件把JSON文本当成普通文本显示,而不是生成对应的下拉选项。

解决步骤:

  1. 遍历AJAX返回的JSON数据,逐个创建<option>元素
  2. 将生成的option添加到select控件中
  3. 调用selectpicker('refresh')刷新控件

修改后的代码示例:

假设你的AJAX返回的JSON数据结构是类似 [{CategoryId: 1, CategoryName: "分类1"}, {CategoryId: 2, CategoryName: "分类2"}] 的数组,修改后的JavaScript代码如下:

function loadCategories() {
    $.ajax({
        url: '../handlers/getcategorylist.ashx',
        data: null,
        method: 'post',
        dataType: 'json',
        success: function (data) {
            const $select = $('#ddlCategories');
            // 可选:清空原有选项(如果不需要保留默认的"Select From The List")
            // $select.empty();
            // 遍历数据生成option
            data.forEach(item => {
                // 根据实际返回的字段调整val和text的属性名
                const option = $('<option>').val(item.CategoryId).text(item.CategoryName);
                $select.append(option);
            });
            // 刷新bootstrap-select控件
            $select.selectpicker('refresh');
        },
        error: function (e) {
            console.log(e.responseText);
        }
    });
}

注意事项:

  • 一定要根据你实际返回的JSON字段调整item.CategoryId和item.CategoryName,比如如果返回的是{id: '1', name: '电子产品'},就改成val(item.id)和text(item.name)
  • 如果需要完全替换原有选项,先调用$select.empty()清空,再添加新选项
  • 使用$('<option>').val().text()的方式比字符串拼接更安全,能避免XSS风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:06:26