簡體   English   中英

我的 ajax 和 php 代碼有什么問題?

[英]what is the problem with my ajax and php code?

我的 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);
?> 

看起來你的錯誤是服務器端的,在那里檢查你的邏輯。 或者,如果您想發布您的服務器端邏輯,我們會看看它:)您在那里發布的內容看起來不錯,沒有立即想到錯誤......

為什么不使用像 JQuery 這樣的框架?
為什么要重新發明輪子?

看看它有多簡單:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    $(this).addClass("done");
  }
});

http://api.jquery.com/jQuery.ajax/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM