12
我想设置我的jQuery用户界面自动完成场从一个Ajax连接有数据。这是我到目前为止的代码:阿贾克斯/ jQuery的自动完成与JSON数据
$("#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 - 微软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
}}))
});
}
});
+1:您还可以使用'$ .map'而不是推的项目进入一个新的数组自己。 –
@AndrewWhitaker你是对的,解决方案更新 –
这工作,谢谢! :)你能解释一下$ .map的作用吗? – Yecats