Ajax / Jquery Autocomplete with JSON data

后端 未结 1 1983
后悔当初
后悔当初 2020-12-29 10:17

I am trying to setup my Jquery UI autocomplete field to have data from an ajax connection. Here is my code so far:

            $(\"#mainIngredientAutoComplet         


        
相关标签:
1条回答
  • 2020-12-29 10:44

    You need to change the success callback to

    response($.map(data, function(v,i){
        return {
                    label: v.MainName,
                    value: v.MainItemID
                   };
    }));
    

    Fiddle.

    The jQuery.map helps to Translate all items in an array or object to new array of items.

    Update: Add Filter

    $("#mainIngredientAutoComplete").autocomplete({
        source: function (request, response) {
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
            $.ajax({
                url: "../api/IngredientChoices",
                dataType: "json",
                success: function (data) {
                    response($.map(data, function(v,i){
                        var text = v.MainName;
                        if ( text && ( !request.term || matcher.test(text) ) ) {
                            return {
                                    label: v.MainName,
                                    value: v.MainItemID
                                   };
                        }
                    }));
                }
            });
        }
    });
    
    0 讨论(0)
提交回复
热议问题