getJSON不以用户类型发送新请求

时间:2017-04-07 14:45:24

标签: javascript jquery getjson

鉴于以下JavaScript,我在用户更改搜索字词时发送新请求时遇到问题。在输入超过3个字符后,它应该只开始搜索/显示结果。它目前只在初始术语超过3个字符后进行一次搜索,但之后不再发送另一个请求。

的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-rest-api.com?q=" + q, {},
      //Get results and make 'em look good
      function(data) {
        console.log(data);
        //  $(".results").append("Results for <b> " + q + "</b>");
        $.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").val() == '') {
              $(".practice-area-results-header, .practice-area-results").empty();
            }
          }
        });
      });
  }  
}); 

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>
        </div>
      </div>
    </div>
  </div>

0 个答案:

没有答案