我正在制作一个实时搜索页面,我认为代码的jquery部分有问题。甚至可能只有#34;小胡子"部分。因为当我检查我的浏览器"网络"页面我可以看到它正在发送到.php页面。但它没有显示任何内容。
我的代码:
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search</title>
</head>
<body>
<p>Search: <input type="text" id="query"></p>
<p>
<input type="radio" name="match_type" value="0"> Begins with |
<input type="radio" name="match_type" value="1"> Ends with |
<input type="radio" name="match_type" value="2" checked> Contains
</p>
<hr/>
<ul id="results"></ul>
<script src="//code.jquery.com/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.min.js"></script>
<script type="mustache/x-tmpl" id="names_tmpl">
{{#names}}
<li>{{name}}</li>
{{/names}}
{{^names}}
<li><em>No matches found</em></li>
{{/names}}
</script>
<script>
$("#query").keyup(function(){
var q = $(this).val();
var match_type = $("input[type=radio]:checked").val();
var data = {query: q, match_type: match_type};
if(q.length == 0 || q == " ") {
return false;
}
$.ajax({
url: "instant-search.php",
data: data,
type: "post",
dataType: "json",
success: function(res) {
var tmpl = $("#names_tmpl").html();
var html = Mustache.to_html(tmpl, res);
$("#results").html(html);
}
});
});
$("input[type=radio]").change(function(){
$("#query").trigger("keyup");
});
$("#query").focus();
</script>
</body>
</html>
instant-search.php(但我觉得那里没有错。没有在这里使用PDO,只是在我的本地主机上检查它)
<?php
class MyDb {
private $db;
public function __construct($host, $username, $password, $dbName) {
$this->db = mysql_connect($host, $username, $password);
mysql_select_db($dbName);
}
public function __destruct() {
mysql_close($this->db);
}
public function select($query) {
return $this->toArray(mysql_query($query));
}
private function toArray($res) {
$arr = array();
while($row = mysql_fetch_array($res)) {
$cols = array();
foreach($row as $key => $val) {
if (is_string($key)) {
$cols[$key] = $val;
}
}
array_push($arr, $cols);
}
return $arr;
}
}
class MatchType {
const BEGINS_WITH = 0;
const ENDS_WITH = 1;
const CONTAINS = 2
}
function processRequest($query, $matchType) {
$db = new MyDb("localhost", "root", "", "search");
$like = "'%{$query}%'";
switch ($matchType) {
case MatchType::BEGINS_WITH:
$like = "'{$query}%'";
break;
case MatchType::ENDS_WITH:
$like = "'%{$query}'";
break;
}
$selectQuery = "SELECT name FROM names WHERE name LIKE {$like} ORDER BY name ASC";
$results = $db->select($selectQuery);
header("content-type: application/json");
echo json_encode(array("names" => $results));
}
$query = $_POST["query"];
$matchType = isset($_POST["match_type"]) ? $_POST["match_type"] : MatchType::CONTAINS;
processRequest($query, $matchType);