我正在尝试对用户进行实时搜索,或者基于查询数据库并返回数组然后在下拉列表中对其进行格式化并使用ajax实时输出给用户。以下是我的代码。问题是我每次运行搜索时suggestions
都应该在div
内再次加载页面。
此外,不会显示搜索结果。
以下是代码:
PHP(与js位于同一页面):
<?php
/* User Search */
if (isset($_POST['userSearch'])):
$string = $_POST['userSearch'];
if (strlen($string) > 3):
$sql = "SELECT id, user_name, user_email, full_name FROM users WHERE MATCH (user_name) AGAINST ({$string}* IN BOOLEAN MODE) ORDER BY user_name LIMIT 10";
$display = '';
if ($result = Nemesis::query($sql)):
$result->fetch_assoc();
$display .= '<ul id="searchresults">';
foreach ($result as $row):
$link = 'index.php?do=users&action=edit&userid=' . (int) $row['id'];
$display .= '<li><a href="' . $link . '">' . $row['user_name'] . '<small>' . $row['full_name'] . ' - ' . $row['user_email'] . '</small></a></li>';
endforeach;
$display .= '</ul>';
print $display;
exit();
endif;
endif;
endif;
?>
JS:
$("#search-input").watermark("Search Username");
$("#search-input").keyup(function () {
var srch_string = $(this).val();
var data_string = 'userSearch=' + srch_string;
if (srch_string.length > 3) {
$.ajax({
type: "post",
url: "",
data: data_string,
beforeSend: function () {
$('#search-input').addClass('loading');
},
success: function (res) {
$('#suggestions').html(res).show();
$("input").blur(function () {
$('#suggestions').customFadeOut();
});
if ($('#search-input').hasClass("loading")) {
$("#search-input").removeClass("loading");
}
}
});
}
return false;
});
CSS:
<style>
/* == Live Search == */
#suggestions{position:absolute;z-index:800;left:20px}
#searchresults{position:relative;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;background-color:#F3F3F3;width:250px;margin-top:7px;left:0;z-index:800;border:1px solid #ccc;background-image:url(../images/td-bg.png);background-repeat:repeat-x;background-position:left top;padding:5px}
#searchresults a small{display:block;line-height:1.2em;color:#999;font-size:12px}
#searchresults a{display:block;text-decoration:none;padding:3px}
#searchresults a:hover{text-decoration:none;background-color:#FFF;border-radius:4px;-moz-border-radius:4px;-webkit-border-radius:4px}
</style>
HTML:
<div id="searchDiv">
<input name="search-input" type="text" class="input" id="search-input" size="40" style="width:240px" onclick="disAutoComplete(this);">
<div id="suggestions"></div>
</div>