php ajax从数据库检索数据

标签 php jquery mysql ajax

我是 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/

相关文章:

mysql - 使用 Groupby 时如何计数?

mysql - 优化 MySQL CREATE TABLE 查询

没有 .php 扩展名的 PHP URL 格式?

javascript - 关于 cookie 爬虫的想法?

javascript - 从选择下拉菜单中触发社交共享弹出窗口

jquery - 超时后停止触发点击事件

mysql - 错误的 MYSQL(日期)输出

php - 有没有办法在 Python 中动态替换正则表达式?

php - 如何让托管服务器及时运行特定的PHP代码?

javascript - 将文本从 div 插入到 sceditor 文本区域中?