我正在尝试一个教程,学习如何使用PHP / jQuery进行即时搜索。我似乎无法找到为什么这段代码无法正常工作。当我将PHP与索引放在同一个文件中之前,这个搜索工作正常,但是当我将它移动到另一个文件时,它就停止了工作。每次按键时,我都会收到此控制台错误消息:ReferenceError: Can't find variable: $_POST
。任何帮助都将深表感谢。
index.php文件
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset-utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function searchkey() {
var searchTxt = $("input[name='search']").val();
$_POST("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search for members..." onkeyup="searchkey();">
<input type="submit" value="Search">
</form>
<div id="output"></div>
</body>
</html>
search.php文件(与index.php相同的位置)
<?php
$connection = mysqli_connect('localhost','root','root','LBD');
$output='';
if(isset($_POST['searchVal'])){
$searchkey= $_POST['searchVal'];
$searchkey=preg_replace("#[^0-9a-z]#i", "", $searchkey);
$query = mysqli_query($connection,"SELECT * FROM members WHERE ownerName LIKE '%$searchkey%' OR companyName LIKE '%$searchkey%'") or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output="There was no search result!";
}
else{
while($row=mysqli_fetch_array($query)){
$oName=$row['ownerName'];
$cName=$row['companyName'];
$output .='<div>'.$oName.'<br/>'.$cName.'</div>';
}
}
}
echo ($output);
?>
答案 0 :(得分:1)
您似乎已经在脚本中使用了PHP $_POST
..
尝试使用:
$.POST
答案 1 :(得分:0)
试试这个
$.ajax({
url: "search.php",
type: 'POST',
data: {
searchVal: searchTxt
},
})
.done(function(output) {
$("#output").html(output);
});