我有一个搜索表单,我想在输入3个字符时通过jQuery自动完成显示建议。建议来自mySQL DB。
会发生什么:jQuery成功地将键入的字符传输到PHP文件,在那里它们成功嵌入到mySQL查询中。
当我用假设的搜索词分别打开PHP文件时,f.e。像这样:/soplogsearch.php?term=xyz
它完美无缺,我看到目标是echo json_encode($return_arr);
的结果
但回到HTML搜索表单文件自动完成并不能提出建议。我在控制台中没有错误。我试图在HTML文件的其他地方回显json_encode,其输出为Null
。
我为(非常简单的)Javascript / jQuery和HTML设置做了一个小提琴:https://jsfiddle.net/9bf6s07f/1/
相关的PHP代码如下所示:
if (isset($_GET['term']))
{
$term = $_GET['term'];
$termwild = "%$term%";
$return_arr = array();
$service = mysql_query("SELECT DISTINCT service FROM master WHERE service LIKE \"" . $termwild . "\"");
while ($data = mysql_fetch_array($service))
{
$return_arr[] = $data[0];
}
json_encode($return_arr);
echo json_encode($return_arr);
}
编辑:为了更快地访问,我在此处包含代码的HTML和jQuery部分,而不是将您链接到小提琴https://jsfiddle.net/9bf6s07f
<body>
<label>Service:</label>
<input type='text' name='' value='' class='auto'>
</body>
和jQuery:
$(document).ready(function() {
$(function() {
$(".auto").autocomplete({
source: "soplogsave.php",
minLength: 3
});
});
});
有人知道我做错了什么吗?我用一组javascript变量分别测试了自动完成,它工作正常。
编辑2:因为所有评论似乎暗示我的PHP错误并且我在控制台中出错,所以我从控制台的网络选项卡中截取了屏幕截图:http://i.imgur.com/i6nAQ98.png
答案 0 :(得分:0)
这就是我在代码中实现它的方式:
<强> PHP 强>
$param = $_GET["term"];
$stk_adddep = "
SELECT * FROM stocktake_products WHERE stocktake_id = '{$stocktake_id}' AND is_deli = 0 AND (product_code LIKE '%{$param}%' OR product_name LIKE '%{$param}%'); ";
//FB::info($stk_adddep);
//echo $stk_adddep;
//die();
$result = db::c()->query($stk_adddep);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['itemCode'] = $row['product_code'];
$row_array['itemDesc'] = $row['product_name'];
//$row_array['itemPrice'] = $row['unit_cost_price'];
array_push( $return_arr, $row_array );
}
/* Free connection resources. */
//mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
然后是javascript
$(document).ready(function(){
// Use the .autocomplete() method to compile the list based on input from user
var url10 = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_cocktails.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>';
$('#itemCode').autocomplete({
source: url10,
minLength: 1,
select: function(event, ui) {
var $itemrow = $(this).closest('tr');
// Populate the input fields from the returned values
$itemrow.find('#itemCode').val(ui.item.itemCode);
$itemrow.find('#itemDesc').val(ui.item.itemDesc);
//$itemrow.find('#itemPrice').val(ui.item.itemPrice);
// Give focus to the next input field to recieve input from user
$('#itemQty').focus();
return false;
}
// Format the list menu output of the autocomplete
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.itemCode + " - " + item.itemDesc + "</a>" )
.appendTo( ul );
};
看看你是否可以将它应用到你的代码中?
答案 1 :(得分:0)
答案发布在用户@ n00dl3的评论中。