再一次,我很难过。我有一个小搜索字段和按钮来搜索mysql数据库。我希望它将结果附加到当前页面,而不是重新加载或加载单独的结果页面。
这是脚本:
<script>
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
//var data = searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
console.log(data);
type: "POST",
url: "do_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
以下是应该附加到ul标签内的原始页面:
<div id="SEARCH2" class="panel">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
这是do_search.php,它应该在ul标签中插入一些html:
<?php
if (isset($_POST['search'])) {
include('db.php');
$word = mysql_real_escape_string($_POST['search']);
$word = htmlentities($word);
$sql = "SELECT id, last_name, first_name, u_name, skype_id, primary_location, phone, status FROM users WHERE (last_name LIKE '%" . $word . "%' OR
first_name LIKE '%" . $word . "%' OR u_name LIKE '%" . $word . "%' OR skype_id LIKE '%" . $word . "%' OR phone LIKE '%" . $word . "%') ORDER BY last_name";
$fetched = mysql_query($sql)or die('query error'.mysql_error());
$end_result = '';
if($fetched){
while($row = MySQL_fetch_array($fetched)):
//TEST TO SEE IF THIS WORKS
$result = $row['id'];
// we will use this to bold the search word in result
$bold = '<span class="found">' . $word . '</span>';
$end_result .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';
endwhile;
echo $end_result;
}
else{
echo '<li>No results found</li>';
}
}
//echo 'crap2';
?>
答案 0 :(得分:1)
从AJAX调用中删除console.log(data);
。如果您不断添加,请从$("#results").html('');
beforeSend:
$.ajax({
type: "POST",
url: "do_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});