Materialize autocomplete with dynamic data in jquery ajax

后端 未结 5 1035
渐次进展
渐次进展 2020-12-30 15:16

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

Here is my code,

相关标签:
5条回答
  • 2020-12-30 15:47

    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

       $(".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.

    0 讨论(0)
  • 2020-12-30 15:47

    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)

    0 讨论(0)
  • 2020-12-30 15:47

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

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

         <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

    0 讨论(0)
  • 2020-12-30 15:56

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

    You can get the list of country names from 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>

    0 讨论(0)
  • 2020-12-30 16:13

    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
                });
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题