我一直在使用jQuery UI Autocomplete从数据库中提出建议并自动完成其余的字段。 这是我的代码。
HTML:
<form action="#" method="post">
<p><label for="kdbr">KDBR</label><br />
<input type="text" name="kdbr" id="kdbr" value="" /></p>
<p><label for="nmbr">NMBR</label><br />
<input type="text" name="nmbr" id="nmbr" value="" /></p>
</form>
Javascript:
$(function() {
//clear values on refresh
$('#nmbr').val("");
$("#kdbr").autocomplete({
source: "<?php echo base_url();?>js/coba3.php",
minLength: 3,
select: function(event, ui) {
$('#nmbr').val(ui.item.nmbr);
}
});
});
PHP:
<?php
$dbhost = 'HOST';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$dbname = 'TBNAME';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$return_arr = array();
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("SELECT * FROM tb_master_barang where kdbr like '%" .mysql_real_escape_string($_GET['term']) . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['kdbr'] = htmlentities(stripslashes($row['kdbr']));
$row_array['nmbr'] = $row['nmbr'];
array_push($return_arr,$row_array);
}
}
mysql_close($conn);
echo json_encode($return_arr);
?>
下拉列表显示来自kdbr
的未定义值的列表。我已单独运行php并返回此值:
[{"kdbr":"950.00.0002","nmbr":"PAKAIAN DINAS KS"},{"kdbr":"950.01.0000","nmbr":"BARANG SCURITY LSNG.PAKAI"},{"kdbr":"950.01.0001","nmbr":"PECI"},{"kdbr":"950.01.0002","nmbr":"KOPEL REM HITAM"},{"kdbr":"950.01.0003","nmbr":"SEPATU PDH"},{"kdbr":"950.01.0005","nmbr":"ROMPI SATPAM"},{"kdbr":"950.01.0006","nmbr":"SEPATU PDL"},{"kdbr":"950.01.0007","nmbr":"TALI KOOR & PLUIT"},{"kdbr":"950.01.0008","nmbr":"PAKAIAN TAHAN API"},{"kdbr":"950.01.0009","nmbr":"HELM TAHAN API"},{"kdbr":"950.02.0001","nmbr":"KAOS SCURITI PNJG\/BED\/LOG DLL"}]
有人可以告诉我我哪里做错了吗?
答案 0 :(得分:0)
您的源字段使用方式有误。您需要传递带有数据的数组或将加载数据的匿名函数。请参阅documentation
这样的事情应该有效:
$("#kdbr").autocomplete({
source: function (request, {
var ajax_url = "<?php echo base_url();?>js/coba3.php?term=" + request.term;
$.ajax({
url: ajax_url,
success: function (response) {
// assuming valid json
var data = $.parseJSON(response);
response($.map(data, function (obj) {
return {
label: obj.name + ': ' + obj.description,
value: obj.name,
id: obj.name
};
}));
}
});
},
minLength: 3,
select: function (event, ui) {
$('#nmbr').val(ui.item.nmbr);
}
});
答案 1 :(得分:0)
试试这个,
select: function(event, ui) {
jQuery.get(ui.item.nmbr);
}