我正在尝试使用JQuery Category Autocomplete (documented here)为我的网站创建一个搜索框,该搜索框将搜索位于“/search_basic.php”的另一个文件中的结果(文件内容如下所示)。我希望将结果分类并缓存在浏览器中以备将来使用。如果没有可用结果,则还应通知用户。除了从远程文件和缓存中提取结果之外,我能够分别执行这些操作。我无法弄清楚如何让我的项目整体运作。
以下是我正在使用的代码:
HTML5:
<div class="ui-widget">
<label for="search">Search: </label>
<input id="search" />
<p id="empty-message"></p>
</div>
CSS3:
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
JQuery的:
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
</script>
<script>
$(function() {
var cache ={};
$( "#search" ).catcomplete({
minLength: 0,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "search_basic.php", request, function( data, status, xhr ) { // Remote results file is located at search_basic.php
cache[ term ] = data;
response( data );
});
// If there are no results notify the user
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
} else {
$("#empty-message").empty();
}
}
});
});
</script>
以下是search_basic.php的内容:
header('Content-Type: application/json');
[
{ "label": "annhhx10", "category": "Products" },
{ "label": "annttop", "category": "Products" },
{ "label": "anders", "category": "People" },
{ "label": "andreas", "category": "People" }
]
提前谢谢!
更新1:我在我的服务器上运行了jQuery UI的远程示例,但是如果没有它返回的额外数据,它就不容易修改。 A working example can be seen here并可以在他们的下载部分下载以查看远程json PHP文件(抱歉,我无法添加更多具有我SO声誉的链接)。
答案 0 :(得分:0)
我认为应该在response
事件中处理空结果的通知:
试试这个:
$(function() {
var cache ={};
$( "#search" ).catcomplete({
minLength: 0,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "search_basic.php", request, function( data, status, xhr ) { // Remote results file is located at search_basic.php
cache[ term ] = data;
response( data );
});
},
response: function(event,ui){
// If there are no results notify the user
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
} else {
$("#empty-message").empty();
}
}
});
});