[英]Autocomplete Text box in 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上找到有關自動完成的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.