使用JSON數據的Ajax / Jquery自動完成


0 Answers

Question

我想設置我的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>

當我開始鍵入“密爾”(牛奶)我的代碼給我這個錯誤:

編輯:

我做了你的改變,這只是一些嘗試,但現在我得到一個新的錯誤 -

[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

                        }}))
                });
            }
        });



Related