使用 jquery ajax 中的动态数据实现自动完成

新手上路,请多包涵

我在 ASP.Net MVC 应用程序中使用 materialize ui,并且我正在使用带有动态数据的自动完成控件。

这是我的代码,

 <div class="row">
    <div class="col s12">
        <div class="row">
            <div class="input-field col s12">
                <i class="material-icons prefix">textsms</i>
                <input type="text" id="autocomplete-input" class="autocomplete">
                <label for="autocomplete-input">Autocomplete</label>
            </div>
        </div>
    </div>
</div>

这是 jquery ajax 调用,

 $(function () {
    $.ajax({
        type: 'GET', // your request type
        url: "/Home/GetData/",
        success: function (response) {
            var myArray = $.parseJSON(response);

            debugger;
            $('input.autocomplete').autocomplete({
                data: {
                    "Arizona (1)": null,
                    "Florida (2)": null,
                    "Georgia (3)": null,
                    "Hawaii(4)": null,
                    "Idaho (5)": null,
                    "Illinois (6)": null
                }
            });
        }
    });
});

它只能接受这种格式的数据,这是我的回应,

 "[["Arizona (1)"],["Florida (2)"],["Georgia (3)"],["Hawaii (4)"],["Idaho (5)"],["Illinois (6)"]]"

如何将我的回复转换为自动完成能够理解的格式?

原文由 AMeh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 267
1 个回答

使用 ajax API 调用实现 materializecss 输入自动完成

我已如下修改以获得国家/地区的自动完成输入。

您可以从 API https://restcountries.eu/rest/v2/all?fields=name 获取国家名称列表

 $(document).ready(function() {
  //Autocomplete
  $(function() {
    $.ajax({
      type: 'GET',
      url: 'https://restcountries.eu/rest/v2/all?fields=name',
      success: function(response) {
        var countryArray = response;
        var dataCountry = {};
        for (var i = 0; i < countryArray.length; i++) {
          //console.log(countryArray[i].name);
          dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
        }
        $('input.autocomplete').autocomplete({
          data: dataCountry,
          limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
        });
      }
    });
  });
});
 <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
  <div class="col s12">
    <div class="row">
      <div class="input-field col s12">
        <label for="country">Autocomplete</label>
        <input type="text" id="country" class="autocomplete">

      </div>
    </div>
  </div>
</div>

原文由 Jaikhlang Brahma 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏