asp.net - Asp.net MVC 中的自动完成文本框
问题描述
我在 asp.net MVC 中工作。我需要一个文本框来通过 ajax 函数自动完成。Ajax 函数不能从控制器调用值。
这是代码:
$( "#birds" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
} );
},
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
} );
解决方案
这是完整的代码:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
var cache = {};
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "Your Controller URL", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
}
});
} );
</script>
您的控制器应该以 JSON 格式响应数据,例如:
[{"id":"Locustella naevia","label":"Common Grasshopper Warbler","value":"Common Grasshopper Warbler"},{"id":"Locustella certhiola","label":"Pallas`s Grasshopper Warbler","value":"Pallas`s Grasshopper Warbler"}]
您的 JSON 应该是动态的,否则,它会响应您相同的 JSON。您应该在响应 AJAX 之前过滤控制器中的数据,并且数据始终采用 JSON 格式。
您可以在https://jqueryui.com/autocomplete/ 和https://jqueryui.com/autocomplete/#remote-with-cache上找到有关自动完成的更多信息
推荐阅读
- python-3.x - sqlite3 错误:您没有为绑定 1 提供值
- uwp - 媒体基础库中的 UWP AAC 编码,未注册类
- php - Bootstrap手风琴在选择另一个后不会折叠
- c# - C# 无法避免嵌套的 try-catch
- docker - 在 Docker 中为 Ubuntu 16.04 运行 Systemd,对于 Ubuntu 18.04 它可以工作
- javascript - 提交表单时通过 JS 验证号码
- mysql - 插入时出错
- angular - 如何在 Ionic 无限滚动中从 Wordpress API 输出累积列表
- pdf - 在浏览器扩展中将 iframe 覆盖在 pdf 文档上
- google-apps-script - Google 表单中的 NA 按钮