我是 ajax 新手,需要帮助从 mysql 表检索数据以显示在搜索框中。
我的 php 表单如下所示
<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input name ="search" type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>
我的搜索查询是这样的
$company_name=mysql_query("SELECT * FROM login
WHERE
(company_name LIKE '" . mysql_real_escape_string($_POST['search']) . "')");
$row = mysql_fetch_assoc($company_name);
$name = $row['company_name'];
我想在部分匹配时将此值传递回我的搜索框。 我走在正确的道路上吗?
最佳答案
您在 JS 中使用 GET
,因此无法通过 php.ini 中的 $_POST
访问变量。在你的 php 中将其更改为 $_GET
或 $_REQUEST
即可工作。除此之外,您的参数是 q
而不是 search
。
关于php ajax从数据库检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767749/