每次请求只在getjson上显示“无结果”

时间:2017-04-09 23:05:13

标签: jquery getjson

当请求响应返回No results时,我正在显示0消息。但是,它会在用户键入时多次显示。当用户输入响应计数大于0的术语时,它不会清除该消息。

的jQuery

$("#results-container").hide();
 $("#global-search").keyup(function(e) {
   var q = $("#global-search").val();
     if(e.which == 13) {
             window.location.replace("/search?q=" + q);
     }
   //Only begin search with at least 3 characters.
   if(q.length > 3){
         $("#results-container").show();
      ajax_search();
   }
   //Send search query
   function ajax_search(){
   $.getJSON("//search.url-to-data.com?q=" + q, {

     },
     //Get results and make 'em look good
     function(data) {
              if(data.count == 0){
                    $(".search-results").hide();
                    $("#results-container").append("<p>No results available. Please try another search.</p>");
                }else{
                    $(".search-results").show();
                }
             $(".practice-area-results, .group-results").empty();
             console.log(data);
         $.each(data.data, function(i, data) {
                     if(data.type === "Practice Area"){
                        $(".practice-area-results").append("<li class='result-item'><a href=\"" + data.permalink + "\">" + data.title + "</a></li>");
                        if($(".practice-area-results").text() === ""){
                            $(".practice-area-results-header, .practice-area-results").empty();
                        }
                     }else if(data.type === "Group"){
             $(".group-results").append("<li class='result-item'><a href=\"" + data.permalink + "\">" + data.title + "</a></li>");
                         if($(".group-results").text() === ""){
                             $(".group-results-header, .group-results").hide()
                         }
                     }
             });
      });
    }
});

HTML

    <div class="row desktop-search">
    <div class="row">
       <div class="col-lg-12">
        <input type="text" class="form-control" id="global-search" style="width:100%; position: fixed;" placeholder="Search...">
      </div>
      <div id="results-container">
        <div class="search-results">
          <p class="practice-area-results-header">Practice Area</p>
          <div class="practice-area-results"></div>
          <p class="group-results-header">Group</p>
          <div class="group-results"></div>
        </div>
      </div>
    </div>
  </div>

0 个答案:

没有答案