我正在设置我的
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,"SubName":"Skim/Fat Free",{"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运行时错误:’data’未定义
$("#mainIngredientAutoComplete").autocomplete({ source: function (request,response) { $.ajax({ url: "../api/IngredientChoices",response: ($.map(data,function(v,i){ return { label: v.MainName,value: v.MainItemID }})) }); } });
您需要将成功回调更改为
原文链接:https://www.f2er.com/ajax/160064.htmlresponse($.map(data,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",success: function (data) { response($.map(data,i){ var text = v.MainName; if ( text && ( !request.term || matcher.test(text) ) ) { return { label: v.MainName,value: v.MainItemID }; } })); } }); } });