12

我正在尝试设置我的 Jquery UI 自动完成字段以获取来自 ajax 连接的数据。到目前为止,这是我的代码:

            $("#mainIngredientAutoComplete").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "../api/IngredientChoices",
                        dataType: "json",
                        success: function (data) {
                            response(function (item) {
                                return {
                                    label: item.MainName,
                                    value: item.MainItemID
                                }
                            });
                        }
                    });
                }
            });

这是我的 JSON:

[{"SubItemID":1,"MainItemID":1,"SubName":"2%","MainName":"Milk"},{"SubItemID":2,"MainItemID":1,"SubName":"Skim/Fat Free","MainName":"Milk"},{"SubItemID":3,"MainItemID":2,"SubName":"Chedder","MainName":"Cheese"}]

HTML:

<table id="tbl_ingredients" style="padding:0px;">
                <tr id="ingHeader">
                    <td>Ingredient</td>
                    <td>Measurement</td>
                    <td>Amount</td>
                    <td><input id="mainIngredientAutoComplete" /></td>
                    <td></td>
                </tr>
</table>

当我开始输入“mil”(牛奶)时,我的代码给了我这个错误:

在此处输入图像描述

编辑:

我进行了更改,尝试了几次,但现在我遇到了一个新错误-

[URL] 中第 55 行第 25 列未处理的异常

0x800a1391 - Microsoft JScript 运行时错误:“数据”未定义

        $("#mainIngredientAutoComplete").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "../api/IngredientChoices",
                    dataType: "json",
                    response: ($.map(data, function(v,i){
                        return {
                            label: v.MainName,
                            value: v.MainItemID

                        }}))
                });
            }
        });
4

1 回答 1

22

您需要将成功回调更改为

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

小提琴

jQuery.map有助于将数组或对象中的所有项目转换为新的项目数组。

更新:添加过滤器

$("#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
                               };
                    }
                }));
            }
        });
    }
});
于 2013-01-24T03:15:28.823 回答