我正在尝试使用AJAX自动完成用户文本。现在我得到了AJAX,以便在用户输入时将“自动完成”功能所需的结果返回给“advice”div。但是,我想要完成的是输入字段(“prod-name”)中的下拉列表,其中提供了作为选项的建议,用户只需单击其首选建议并使其成为输入的“值”(类似)谷歌如何在您键入时提供搜索建议,但是简化版本。)
我的标记很远:
<script type="text/javascript">
function search(searchword) {
$('#suggestion').load('invoice-get-data.php?searchword=' + searchword);
}
</script>
</head>
<body>
<div class="prod-name">
<input onKeyPress="search(this.value)" type="text" id="prod-name"/>
<div id="suggestion"></div>
</div>
</body>
到目前为止我的AJAX代码(invoice-get-data.php代码段)
$searchword = $_GET['searchword'];
$results = mysql_query("SELECT * FROM products WHERE prod_name LIKE '".$searchword."%'") or die(mysql_error());
while($row = mysql_fetch_array($results)){
echo $row['prod-name'] . '<br>';
}
答案 0 :(得分:1)
jquery ui为此类自动完成提供了一个小部件:http://jqueryui.com/autocomplete/。
javascript方面是:
<script>
$(function() {
$( "#prod-name" ).autocomplete({
source: "invoice-get-data.php",
minLength: 2,
select: function( event, ui ) {
alert("Product #" + ui.item.id + " selected");
return true;
}
}
});
});
</script>
PHP方面将是:
$searchword = $_GET['term'];
$results = mysql_query("SELECT * FROM products WHERE prod_name LIKE '".$searchword."%'") or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($results)){
$data[] = array(
"id" => $row['id'],
"value" => $row['prod-name'],
"label" => $row['prod-name']
);
}
echo json_encode($data);