使用jquery ajax中的动态数据实现自动完成
我正在ASP.Net MVC应用程序中使用materialize ui,我正在使用带有动态数据的自动完成控件。
这是我的代码,
textsms
这是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)"]]"
如何将我的响应转换为自动完成理解的格式?
使用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. }); } }); }); });
不是很花哨,但试一试:
$(function () { $.ajax({ type: 'GET', // your request type url: "/Home/GetData/", success: function (response) { var myArray = $.parseJSON(response); var dataAC = {}; for(var i=0;i
美好的一天。 我可以建议一个不同的方法。 实现自动完成具有方法
了updateData
因此,如果我们想要获取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); } }); }); });
不适合不同的数据源,但可能是一个起点。
您可以使用Devberidge插件轻松实现自动完成function。
使用https://github.com/devbridge/jQuery-Autocomplete获取Devbridge插件
这里getCountry.php文件返回JSON数据。 欲了解更多信息,请访问https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php