【发布时间】:2020-05-14 22:14:41
【问题描述】:
我正在使用Twitter TypeAhead plugin 0.11,我想在 DIV 中显示一条消息“未找到结果”,但是我根据文档插入的代码不起作用。我发现了一些类似的问题,我没有找到解决这个问题的正确方法:
- twitter bootstrap typeahead ajax example
- jQuery Ajax error handling, show custom exception messages
- Twitter Typeahead with template always return only 1 row of data
- 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