我希望使用AJAX进行自动完成。但是当我在文本框中输入时,它不会显示任何内容。如果你发现问题会很棒。
<html>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<link rel="stylesheet" href="css/jquery-ui-1.10.3.custom.min.css" />
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript">
$('#item_1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'item_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#code_1').val(names[1]);
$('#description_1').val(names[2]);
$('#quantity_1').val(names[3]);
}
});
</script>
</head>
<body>
<form action="" method="post" >
<input type="text" name="item[]" id="item_1" class="ui-autocomplete-input">
<input type="text" name="code[]" id="code_1" class="ui-autocomplete-input">
<input type="text" name="description[]" id="description_1" class="ui-autocomplete-input">
<input type="text" name="quantity[]" id="quantity_1" class="ui-autocomplete-input">
</form>
</body>
</html>
AJAX.PHP 我的查询何时会找到搜索关键字,并会自动显示在多个文本框中。
require_once 'dbconnection.php';
if($_POST['type'] == 'item_table'){
$row_num = $_POST['row_num'];
$result = mysqli_query($conn, "SELECT item, code, description, quantity FROM item_tb where item LIKE '".strtoupper($_POST['name_startsWith'])."%'");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['item'].'|'.$row['code'].'|'.$row['description'].'|'.$row['quantity'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
?>
答案 0 :(得分:0)
我在一段时间之前在网站上完成了此操作,请检查其标题的搜索栏:http://jhm.co.nz/
我为你定制了, 我的json看起来像:
[
{"id":"1","type":"product","name":"Q10 Soy oner"},
{"id":"3","type":"product","name":"SoyLotion Toner"}
]
我的脚本是:
$(function() {
$( "#headerSearch" ).autocomplete({
minLength: 1,
source: 'https://www.jhm.co.nz/ajaxSearch.php',
focus: function( event, ui ) {
name = ui.item.name;
$( "#headerSearch" ).val( name );
return false;
},
select: function( event, ui ) {
$( "#headerSearch" ).val( ui.item.name );
$( "#headerSearchId" ).val( ui.item.id );
$( "#headerSearchType" ).val( ui.item.type );
return false;
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
document.getElementById('headerSearch').className='ui-autocomplete-input';
return $( "<li>" ).append( "<a>" + item.name + "</a>" ).appendTo( ul );
};
})
#headerSearchId,#headerSearchType是隐藏字段的id,在我的例子中,你只需要输入3个输入文本字段并给它们像#headerSearch,#headerSearchId,#headerSearchType,自动完成将在#headerSearch上应用,还需要修改你的json,就像我上面一样。