Update
我刚刚发布了一个示例项目,在 GitHub 的文本框中展示了 jQueryUI 自动完成功能https://github.com/alfalfastrange/jQueryAutocompleteSample
我将它与常规 MVC TextBox 一起使用,例如
@Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", @class = "ui-widget TextField_220" })
这是我的 Ajax 调用的剪辑
它首先检查其内部缓存的正在搜索的项目,如果没有找到,它会向我的控制器操作发出 Ajax 请求以检索匹配的记录
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
这不是全部代码,但您应该能够在这里看到如何搜索缓存,然后进行 Ajax 调用,然后如何处理响应。我有一个select
部分,这样我就可以用选定的值做一些事情