我以前从未使用过ajax,并且正在尝试完全理解这个与我想要做的类似的示例。这是我对示例代码的疑问。
我需要包含某种 ajax header 脚本才能使用它吗???
这部分在 html 文件中的作用:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
这是我遇到的最大问题。 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);
?>
最佳答案
- 没有。这是 EMCAScript 中的标准规范。
- 该特定代码行打开
GET
请求getuser.php
文件,传递 GET 参数q
作为str
的值在你的 JS 中。 - 在该特定实例中,$q 被设置为
GET
的值q
的值.
简而言之,您的 JS 调用 PHP 脚本来执行自身,同时传递变量以(表面上)修改脚本的结果。
如果你不明白GET
和POST
变量,我建议至少阅读 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/