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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39883425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:01:08  来源:igfitidea点击:

Materialize autocomplete with dynamic data in jquery ajax

javascriptjqueryajaxautocompletematerialize

提问by AMeh

I'm using materialize ui in an ASP.Net MVC application and I'm using an autocomplete control with dynamic data.

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

Here is my code,

这是我的代码,

<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>

This is the jquery ajax call,

这是 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
                }
            });
        }
    });
});

It can accept data only in this format and this is my response,

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

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

How do I convert my response into the format that autocomplete understands?

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

回答by Jaikhlang Brahma

Using ajax API call for materializecss input autocomplete
I have modified as below to obtain autocomplete input for Countries.

使用 ajax API 调用 materializecss 输入自动完成
我已修改如下以获得国家的自动完成输入。

You can get the list of country names from API https://restcountries.eu/rest/v2/all?fields=name

您可以从 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>

回答by George Dgebuadze

Good day. I can suggest a little different approach. Materialize autocomplete has method

再会。我可以建议一些不同的方法。实现自动完成有方法

updateData

更新数据

So if we want to get ajax to load data, we may add event listener to input field

所以如果我们想让ajax加载数据,我们可以在输入字段中添加事件监听器

   $(".autocomplete").each(function () {
    let self = this;
    $(this).autocomplete();
    $(this).on("input change", function () {
        $.ajax({
            url: '/source/to/server/data',
            type: 'post',
            cache: false,
            data: {"some": "data"},
            success: function (data) {
                data = JSON.parse(data);
                $(self).autocomplete("updateData", data/*should be object*/);
            },
            error: function (err) {
                console.log(err);
            }
        });
    });
});

Not ideal for different data sources, but may be a starting point.

对于不同的数据源并不理想,但可能是一个起点。

回答by JC Hernández

Not very fancy, but give it a try:

不是很花哨,但试一试:

$(function () {
    $.ajax({
        type: 'GET', // your request type
        url: "/Home/GetData/",
        success: function (response) {
            var myArray = $.parseJSON(response);
            var dataAC = {};
            for(var i=0;i<myArray[0].length;i++){
                eval("dataAC." + myArray[0][i] + " = null;");
            }
            debugger;
            $('input.autocomplete').autocomplete({
                data: dataAC
            });
        }
    });
});

回答by Abhishek Singh

Try to convert your response through this way, in your case you don't need the first line of code.

尝试通过这种方式转换您的响应,在您的情况下,您不需要第一行代码。

var responseData = JSON.parse(`[["Arizona (1)"],["Florida (2)"],["Georgia (3)"],["Hawaii (4)"],["Idaho (5)"],["Illinois (6)"]]`);

var acArray = [];
var acData = {};
responseData.forEach(res => {
  acArray.push(res.join())
})
acArray.forEach(acObj => {
  acData[acObj] = null;
})
console.log(acData)

回答by Bharathiraja

you can easily achieve the autocomplete functionality using the Devberidge plugin.

您可以使用 Devberidge 插件轻松实现自动完成功能。

Get Devbridge plugin using https://github.com/devbridge/jQuery-Autocomplete

使用https://github.com/devbridge/jQuery-Autocomplete获取 Devbridge 插件

     <script type="text/javascript">

    $(document).ready(function() {


              $("#country").devbridgeAutocomplete({
                //lookup: countries,
                serviceUrl:"getCountry.php", //tell the script where to send requests
                  type:'POST',


                  //callback just to show it's working
                  onSelect: function (suggestion) {
                     // $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
                    },
                showNoSuggestionNotice: true,
                noSuggestionNotice: 'Sorry, no matching results',


              });

    });

  </script>

Here the getCountry.php file returns the JSON data. For more info visit https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php

这里 getCountry.php 文件返回 JSON 数据。有关更多信息,请访问https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php