无法从数据库获取结果..! 这是我的 Index.html
<html>
<head>
<title>Live Search</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function findName(str)
{
$.POST("names.php",{partialName:str},function(data));
$("#result").innerHtml=data;
}
</script>
</head>
<body>
<center>
Enter The Name: <input type="text" onkeypress="findName(this.value)">
<br>
<div id="result">
</div>
</center>
</body>
这是名称.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$name=$_POST['partialName'];
$result=mysql_query("SELECT fname FROM name where fname LIKE '%$name';")or die(mysql_error());
while($list=mysql_fetch_array($result))
{
echo "<div>".$result['fname']."</div>";
}
?>
我在检查元素时遇到的错误是: Uncaught ReferenceError :findName 未定义 onkeypress @ (index):16
最佳答案
此行 $.POST("names.php",{partialName:str},function(data));
将引发错误(检查控制台)
SyntaxError: expected expression, got ')'
ReferenceError: findName is not defined
检查jQuery POST看到它
这是一个快速修复(也将名称添加到输入中):
<script type="text/javascript">
function findName(str)
{
$.ajax({
type: "POST",
url: "names.php",
data: {
partialName: str
},
success: function(data){
$("#result").html(data);
}
});
}
</script>
HTML:
<input type="text" name="str" onkeypress="findName(this.value)" />
关于javascript - 使用 Ajax 进行实时搜索时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43818908/