【问题标题】:Select2 Drop Down To Display Pre Fetched DataSelect2 下拉显示预取数据
【发布时间】:2017-04-05 18:25:35
【问题描述】:

我有以下代码:

<hr class="col-sm-10"/>
<form class="col-sm-10 form-horizontal">
    <div class="form-group">
        <label for="test" class="control-label col-sm-2">Name</label>
        <div class="col-sm-10">
            <select class="col-sm-10 form-control" id="tenantList">

            </select>
        </div>
    </div>
</form>

<script>
    var tenants = [];
        $.ajax({
                url: 'api/Tenant'
            })
            .done(function (data) {
                tenants = data;
            })
            .fail(function () {
                console.log("Problem :(");
            });

    $('#tenantList').select2({
        placeholder: "Select a tenant",
        allowClear: true,
        data: tenants
    });
</script>

tenants 变量未设置为返回的 JSON 数组。数据成功来自服务器,但变量仍然为空。我究竟做错了什么?在 Select2 中正确的做法是什么?

【问题讨论】:

  • 你试试先回答?
  • @ChristianCarrillo 感谢您的回复。不幸的是,我需要阅读有关 Select2 的更多信息。我的回复不是和文本属性。阅读如何处理这种情况

标签: jquery asp.net-mvc-4 jquery-plugins jquery-select2


【解决方案1】:

将 select2 指令移到完成的 ajax 中

<hr class="col-sm-10"/>
<form class="col-sm-10 form-horizontal">
    <div class="form-group">
        <label for="test" class="control-label col-sm-2">Name</label>
        <div class="col-sm-10">
            <select class="col-sm-10 form-control" id="tenantList">

            </select>
        </div>
    </div>
</form>

<script>
    var tenants = [];
        $.ajax({
                url: 'api/Tenant'
            })
            .done(function (data) {
                tenants = data;
                $('#tenantList').select2({
                  placeholder: "Select a tenant",
                  allowClear: true,
                  data: tenants
                });
            })
            .fail(function () {
                console.log("Problem :(");
            });


</script>

【讨论】:

    【解决方案2】:

    获取数据后,需要将ajax返回的数据赋值给select2的'data':

    function callajax() {
      $.ajax({
          url: 'api/Tenant'
        })
        .done(function(data) {
          $('#tenantList').select2({
            placeholder: "Select a tenant",
            width: "200px",
            allowClear: true,
            data: data
          });
        })
        .fail(function() {
          console.log("Problem :(");
        });
    }
    
    callajax();
    

    希望对你有帮助

    https://jsfiddle.net/dalinhuang/3bmf11x7/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多