我想创建一个jQuery字段,当我输入时会自动填充用户名,这是我的代码:
首先是我的jQuery脚本:
<script>
$(document).ready(function(){
$('#search').typeahead({
source: function(query, process) {
$.ajax({
url: 'func/autocomplete.php'
type: 'POST';
data: 'query=' + query;
dataType: 'JSON';
async: true;
success: function(data) {
process(data);
}
});
}
});
});
</script>
第二种形式:
<div class="container">
<div class="ribbon">Change player's IP(UCP Whitelist)</div>
<table border="1" cellspacing="15" align="center">
<tr>
<form action='func/changeip.php' method='POST' class="navbar-search">
<td><input type='text' class="search-query span3 pull-right" placeholder='Account Name' name='username' id='search' data-provide="typeahead"></td>
<td><input type='text' placeholder='ex. 192.162.1.20' name='ip' id='ip'></td>
<td><input type='submit' value='Change IP'></td>
</form>
</tr>
</table>
</div>
第三个是我的autocomplete.php:
<?php
include '../includes/connect.php';
if (isset($_POST['query'])) {
$query = $mysqli->real_escape_string($_POST['query']);
$sql = $mysqli->query("SELECT * FROM accounts WHERE Username LIKE '%{$query}%'");
$array = array();
while ($row = fetch_assoc($sql)) {
$array[] = $row['Username'];
}
echo json_encode($array);
}
?>
现在,说实话。它简单不起作用。我做错了什么,我该如何解决?
答案 0 :(得分:1)
请试试这个: 您的脚本应如下所示:
<script>
$(document).ready(function(){
$("#search").on("keyup", function(){
$.ajax({
url: 'func/autocomplete.php',
type: 'POST',
data: {query: $(this).val()},
success: function(data) {
process(data);
}
});
});
});
</script>
在你的PHP文件中,请在文件的第一行添加:
header('Content-Type: application/json');
以下两个文件可帮助您了解该过程。复制它们并测试它们是否有效。 的 stackoverflow.php 强>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#search").on("keyup", function(){
var searchedText = $(this).val();
if (searchedText.length>=2){
$.ajax({
url: 'stack_autocomplete.php',
type: 'POST',
data: {query: $(this).val()},
success: function(data) {
$("#search").val(data);
}
});
}
});
});
</script>
</head>
<body>
<div class="container">
<div class="ribbon">Change player's IP(UCP Whitelist)</div>
<table border="1" cellspacing="15" align="center">
<tr>
<form action='func/changeip.php' method='POST' class="navbar-search">
<td><input type='text' class="search-query span3 pull-right" placeholder='Account Name' name='username' id='search' data-provide="typeahead"></td>
<td><input type='text' placeholder='ex. 192.162.1.20' name='ip' id='ip'></td>
<td><input type='submit' value='Change IP'></td>
</form>
</tr>
</table>
</div>
</body>
和 stack_autocomplete.php
<?php
header('Content-Type: application/json');
$array = array("ana","alex","andrei");
$answer = "Nothing found.";
foreach ($array as $key => $value) {
if (strpos($value,$_POST['query'])!==false) $answer = $value;
}
echo json_encode($answer);
exit();
?>
请将这两个文件放在测试目录中并访问 stackoverflow.php 。然后在搜索框中输入以下名称之一:alex | ana |安德烈