【发布时间】:2026-01-24 00:40:01
【问题描述】:
我的 ajax 和 php 代码有什么问题?它总是显示无法连接到mysql。我的 wamp 服务器已经打开,但为什么它不能运行?我用connect mysql尝试了我的其他代码,它成功了。
客户端:
<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">oscar</option>
<option value="2">charles</option>
<option value="3">fathur</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
服务器端
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'user', 'user123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("showuser", $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);
?>
【问题讨论】:
-
听起来错误出在您的 PHP 代码中,所以如果您可以发布该代码,我们可能会更有帮助。
-
请贴出getuser.php的内容
-
一般来说,我喜欢退出 php,而不是使用 echo 的实际 html。我认为它确实允许更简洁的代码,但这取决于你。