我的ajax和php代码有什么问题?它始终显示无法连接到mysql。我的wamp服务器已经打开,但为什么它不能运行?我尝试连接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);
?>
答案 0 :(得分:0)
看起来您的错误是服务器端,请检查您的逻辑。或者,如果你想发布你的服务器端逻辑,我们会偷看它:)你在那里发布的内容看起来很好,没有立即出现错误......
答案 1 :(得分:-1)
为什么不使用像JQuery这样的框架?
为什么重新发明轮子?
看看它有多简单:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});