简体   繁体   English

使用 url 从 jQuery UI 自动完成获取列表选项

[英]Get list options from jQuery UI autocomplete with url

My element is a jQuery autocomplete element that gets its options from a URL:我的元素是一个 jQuery 自动完成元素,它从 URL 获取其选项:

$element.autocomplete({
    source: '/mysearchurl',
    open: function () {
        //...
    },
    response: function (event, ui) {
        //...
    },
    select: function (event, ui) {
        //...
    }
});

It works as expected: The user enters some characters, and it displays the matching values in a drop-down.它按预期工作:用户输入一些字符,并在下拉列表中显示匹配的值。

What I want now, in my Javascript, is to get the options out of the list, ideally as the same JSON that it gets from the URL.我现在想要的是,在我的 Javascript 中,从列表中获取选项,最好是从 URL 中获取的相同 JSON。 I could try to collect them from the element through something like this:我可以尝试通过这样的方式从元素中收集它们:

$($element.data('ui-autocomplete').menu.element[0].list.childNodes).each()

But maybe there's a better way?但也许有更好的方法?

I propose to use source function with an Ajax call inside:我建议在内部使用带有 Ajax 调用的函数:

 $("#autocomplete").autocomplete({ source: function(request, response) { var el = this.element; var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i"); $.ajax({ url: "https://api.myjson.com/bins/qnhcd", type: "GET", contentType: "application/json", dataType: "json", success: function(data, textStatus, jqXHR) { var selection = data.filter(function(item) { if (matcher.test(item.value)) return item.value; }); el.data("source", selection); response(selection); } }); } }); $( "#autocomplete" ).on( "autocompleteresponse", function( event, ui ) { refreshList(); }); refreshList = function() { var source = $("#autocomplete").data("source"); console.log("refreshList", source); $("#list").empty(); if (source) { for (var i in source) { $("#list").append("<li>" + source[i].value + "</li>") } } else { $("#list").append("<li>No options</li>") } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" /> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <label for="autocomplete">Select a programming language: </label> <input id="autocomplete"> <br> <button onclick="refreshList()"> refresh list </button> <br> <ol id="list"> </ol>

here is a jsfiddle: http://jsfiddle.net/beaver71/svLsw13f/这是一个 jsfiddle: http : //jsfiddle.net/beaver71/svLsw13f/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM