我正在尝试使用bootstrap,php和ajax进行自动完成。
我的PHP代码似乎就在这里代码:
<?php
$conn = pg_connect("host=y dbname=y user=y");
$data = array();
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$result = pg_query_params($conn, "select name from users_table where users_table.name like $1", array($search_param));
while($row = pg_fetch_row($result)) {array_push($data, $row[0]);}
echo json_encode($data);
$conn->close();
?>
通过简单的测试$search_param = '%S%';
,这是我从php文件输出的内容:
["Steven","Sally","Sam","Susan"]
这是我的index.php文件:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Autocomplete Textbox using Bootstrap Typeahead with Ajax PHP</h2>
<br /><br />
<label>Search Name</label>
<input type="text" name="name" id="name" class="form-control input-lg" autocomplete="off" placeholder="Type Name" />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#name').typeahead({
source: function(query, result)
{
$.ajax({
url:"autoComplete.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
但是我的自动完成功能根本不起作用,我可以理解为什么。怎么了?