gpt4 book ai didi

asp.net - Asp.net MVC 中的自动完成文本框

转载 作者:行者123 更新时间:2023-12-04 10:43:12 25 4
gpt4 key购买 nike

我在 asp.net MVC 工作。我需要一个文本框来通过 ajax 函数自动完成。
Ajax 函数无法从 Controller 调用值。

这是代码:

 $( "#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>

您的 Controller 应该以 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 之前,您应该过滤 Controller 中的数据,并且数据始终采用 JSON 格式。

您可以在 https://jqueryui.com/autocomplete/ 上找到有关自动完成的更多信息
& https://jqueryui.com/autocomplete/#remote-with-cache

关于asp.net - Asp.net MVC 中的自动完成文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59836879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com