0

我有一个搜索地点的代码。服务器以 json 格式正确返回数据,但 typeahead 未显示结果。

<script type="text/javascript">
$(document).ready(function(e) {
    $('#txt_ser').typeahead({
      minLength:1,
      source: function (query, process) {
          var places = [];
          var map = {};
          $.ajax({
              dataType: "json",
              url: "<?php echo base_url() . "ajax/ser";?>",
              data: 'q='+query,
              type: 'POST',
              success: function (data) {
                  $.each(data, function(i, place){
                      map[place.yt_center_state] = place;
                      places.push(place.yt_center_state);
                  });
                  return process(places);
               }
          })
      }
    });
});
</script>

服务器以 json 格式返回数据,当键入关键字 pune 时,示例如下所示

0: {yt_center_top_city:pune, yt_center_state:MH}
1: {yt_center_top_city:pune, yt_center_state:MH}
2: {yt_center_top_city:pune, yt_center_state:MH}
3: {yt_center_top_city:pune, yt_center_state:MH} 
4

1 回答 1

0

You didn't return the result of your ajax request to typeahead source. This line of your code:

 return process(places);

is inside success handler of $.ajax, so it only returns the places to that function.

You should change your code to:

$('#txt_ser').typeahead({
  minLength:1,
  source: function (query, process) {
      var places = [];
      var map = {};
      return $.ajax({   // <- add return here
          dataType: "json",
          url: "<?php echo base_url() . "ajax/ser";?>",
          data: 'q='+query,
          type: 'POST',
          success: function (data) {
              $.each(data, function(i, place){
                  map[place.yt_center_state] = place;
                  places.push(place.yt_center_state);
              });
              return process(places);
          }
      });
  }
});

Hope it helps

于 2013-07-25T22:33:59.780 回答