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

Laravel 8项目中Select2展示结果但首次选择后无法选中如何解决

问题原因

  • Select2配置层级错误:theme、placeholder、tags属于Select2的全局配置参数,你错误将其定义在了ajax属性内部,导致组件初始化后状态管理逻辑异常,首次选中后无法识别后续的选择操作。
  • 可选排查项:如果你的currents表中current_code字段存在重复值或者空值,也会导致Select2选项匹配失败,出现无法选中的问题。

修复方案

1. 修正JS代码的配置结构

将全局配置项从ajax内部移出,修正后的代码如下:

$('#gondericiAdi').select2({
    theme: "bootstrap4",
    placeholder: "Select an option",
    tags: true,
    allowClear: true, // 可选配置,支持清空已选内容
    ajax: {
        url: "/MainCargo/GetCurrents",
        type: "post",
        dataType: 'json',
        delay: 1000,
        data: function (params) {
            return {
                _token: token,
                currentSearchTerm: params.term,
                page: params.page || 1
            };
        },
        processResults: function (response) {
            return {
                results: response
            };
        },
        cache: true
    }
});

2. 可选优化HTML结构

为了让placeholder正常生效,建议在select标签内添加空的option占位符:

<select class="form-control" name="" style="width:100%;" id="gondericiAdi">
    <option value=""></option>
</select>

3. 后端返回校验

确认PHP接口返回的每条数据的id(对应current_code)都是唯一非空值即可,现有业务逻辑无需额外修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 01:45:04