php - 使用 php 和 javascript AJAX 连接到数据库

标签 php javascript mysql html ajax

我以前从未使用过ajax,并且正在尝试完全理解这个与我想要做的类似的示例。这是我对示例代码的疑问。

  1. 我需要包含某种 ajax header 脚本才能使用它吗???

  2. 这部分在 html 文件中的作用:

    • xmlhttp.open("GET","getuser.php?q="+str,true);
    • xmlhttp.send();
  3. 这是我遇到的最大问题。 q是什么?是值 ex:1, 2,3 等吗??

    • $q=$_GET["q"];

这是 html 文件......

<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  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 (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

这是名为 getuser.php 的 php 文件...

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

最佳答案

  1. 没有。这是 EMCAScript 中的标准规范。
  2. 该特定代码行打开 GET请求getuser.php文件,传递 GET 参数 q作为 str 的值在你的 JS 中。
  3. 在该特定实例中,$q 被设置为 GET 的值q 的值.

简而言之,您的 JS 调用 PHP 脚本来执行自身,同时传递变量以(表面上)修改脚本的结果。

如果你不明白GETPOST变量,我建议至少阅读 the PHP manual's page on the $_GET array ,或a more general overview of GET and POST variables .

关于php - 使用 php 和 javascript AJAX 连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11919091/

相关文章:

php - "Tie"已上传图片至其余部分

javascript - 在 Ember 中,使用选择标签停止点击事件传播的最佳方法是什么

javascript - 如何将此 SVG 三 Angular 形转换为 "wandering"路径表示?

javascript - 用反斜杠替换所有未转义的字符匹配

mysql - 使用表名作为新字段组合两个(多个)表

php - 我应该在 MySQL 还是 PHP 中执行正则表达式过滤?

php - 如何在 Apache 中将 php 文件显示为纯文本

用于检查用户名和密码字段的 Javascript 函数,如果它们没有相应地完成则停止

php - 如何从 PHP 中的数组中检索数据

mysql - Laravel 检查字符串是否包含数据库中的单词