2010-11-10 41 views
5

我有以下代码:jQuery UI的自动完成功能,显示的东西时,没有结果

// Autocomplete search 
    $("#shop_search").autocomplete({ 
     source: '<%= spotify_search_path(:json) %>', 
     minLength: 1, 
     select: function(event, ui) { 
     append_place(ui.item.name, ui.item.id, ui.item.shop_type, ui.item.address_geo, ui.item.contact, ui.item.email, ui.item.web); 
     $("#shop_search").val(''); 
     } 
    }).data("autocomplete")._renderItem = function(ul, item) { 
     return $("<li></li>") 
     .data("item.autocomplete", item) 
     .append("<a>" + "<span class='autocomplete_link'>" + item.name + "</span>" + "<br />" + "<span class='autocomplete_address'>" + item.address_geo + "</span>" + "</a>") 
     .appendTo(ul); 

     $(".ui-autocomplete-loading").ajaxStart(function(){ 
     $(this).show(); 
     }); 

     $(".ui-autocomplete-loading").ajaxStop(function(){ 
     $(this).hide(); 
     }); 

    }; 

目前它只显示下拉自动完成时,有搜索结果。如果找不到任何内容,我希望它显示“找不到匹配项”。我应该在代码中添加什么?

谢谢。

回答

18

如果您对源使用jQuery ajax调用,则可以在结果中附加“找不到结果”(如果没有)。然后,在select方法中,您可以简单地检查该项目是否为您添加的“找不到结果”项目,如果是,则不执行任何操作。在这里,我通过检查id是否等于零来确定。

$("#shop_search").autocomplete({ 
    source: function (request, response) { 
     $.ajax({ 
      url: "<%= spotify_search_path(:json) %>", 
      data: { 
       term: request.term 
      }, 
      success: function (data) { 
       if (data.length == 0) { 
        data.push({ 
         id: 0, 
         label: "No results found" 
        }); 
       } 
       response(data); 
      } 
     }); 
    }, 
    select: function (event, ui) { 
     if (ui.item.id != 0) { 
      append_place(ui.item.name, ui.item.id, ui.item.shop_type, ui.item.address_geo, ui.item.contact, ui.item.email, ui.item.web); 
      $("#shop_search").val(''); 
     } 
    } 
}); 

你需要做你的模板一些工作,以获得正确地显示“没有发现任何结果”,但这应该让你在正确的轨道上。

0

您可以检查项目是否为零或0. 如果项目为0或null追加“找不到匹配项”否则附加项目。这基本上是整个逻辑。

0

可能这有助于

source: function(request, response) { 
    $.getJSON(url, { 
     term: extractLast(request.term) 
    }, response) 
    .error(function() { 
     console.log("no results"); 
    }); 
}, 
0
$("#jsonNameSearch").autocomplete({ 
    // This is the source of the autocomplete, in the success method if the 
    // length of the response is zero then highlight the field indicating no match. 
    source: function(request, response) { 
     $.getJSON('jsonAutocomplete.ajax?dataType=drivers', { 
      term: request.term 
     }, response) 
     .success(function(data) { 
      (data.length == 0) ? $("#jsonNameSearch").addClass('nomatch') : $("#jsonNameSearch").removeClass('nomatch'); 
     }); 
    },  
    select: function(event, ui) {   
     if (ui.item) self.location.replace('driverModify.htm?id='+ui.item.id);   
    }   
}); 
+1

这将会是更好的,如果你解释你发布的代码。 – 2012-10-27 00:11:35