【问题标题】:Twitter Typeahead: How to show "Result not found" message into a DIV?Twitter Typeahead:如何在 DIV 中显示“未找到结果”消息?
【发布时间】:2020-05-14 22:14:41
【问题描述】:

我正在使用Twitter TypeAhead plugin 0.11,我想在 DIV 中显示一条消息“未找到结果”,但是我根据文档插入的代码不起作用。我发现了一些类似的问题,我没有找到解决这个问题的正确方法:

  1. twitter bootstrap typeahead ajax example
  2. jQuery Ajax error handling, show custom exception messages
  3. Twitter Typeahead with template always return only 1 row of data
  4. typeahead empty template not working

我尝试使用的参数是“模板{空:”。以下是我在我的项目中使用的typeahead和ajax代码:

HTML 代码:

<label>Search Country</label>
   <input type="text" name="country" id="country" class="form-control input-lg" autocomplete="off" placeholder="Type Country Name" />
<div id="message"></div>

TypeAhead 和 Ajax 代码:

<script>
$(document).ready(function(){

 $('#country').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data)
    {
     result($.map(data, function(item){
      return item;
     }));
    }

   })
  },

  templates: {
        empty: function(data){

          $('#message').text('Country not found');
        }},

 });

});
</script>

最后,PHP代码 fetch.php 将结果返回到ajax:

<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$request = ($connect, $_POST["query"]);
$query = "
 SELECT * FROM countries WHERE name LIKE '%".$request."%'
";

$result = mysqli_query($connect, $query);

$data = array();

if(mysqli_num_rows($result) > 0)
{
 while($row = mysqli_fetch_assoc($result))
 {
  $data[] = $row["name"];
 }
 echo json_encode($data);
}

?>

上面的所有代码都可以正常工作,但是当我在预先输入参数“source”之后插入下面的代码时,当我在输入“#country”中输入错误时没有任何反应“

templates: {
        empty: function(data){

          $('#message').text('Country not found');
        }},
在这种情况下,可以在div中显示“没有结果 em>”。

【问题讨论】:

    标签: javascript jquery html ajax typeahead.js


    【解决方案1】:

    我认为您需要使用notFound 而不是empty

    另外,我认为options 参数是必需的,但可以是null。所以你应该这样称呼它.typeahead(null, { source: ..., templates: { notFound: ... } })

    【讨论】:

      猜你喜欢
      • 2013-12-25
      • 2012-05-31
      • 2015-08-28
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      相关资源
      最近更新 更多