2014-03-26 57 views
0

我想用AJAX查詢我的MySQL數據庫。 html表格被構建,但MySQL數據不顯示。我不知道我錯過了什麼。我有2個文件。到目前爲止,這是我:PHP AJAX MySQL查詢問題

ajax1.html

<html> 
<head> 
<script> 
function showUser(str) 
{ 
if (str=="") 
{ 
document.getElementById("txtHint").innerHTML=""; 
return; 
} 

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">612</option> 
<option value="2">614</option> 
<option value="3">640</option> 
<option value="4">641</option> 
</select> 
</form> 
<br> 
<div id="txtHint"><b>Results</b></div> 

</body> 
</html> 

和getuser.php

<?php 
$q = intval($_GET['q']); 

$con = mysqli_connect('localhost','root','password','data'); 
if (!$con) 
{ 
    die('Could not connect: ' . mysqli_error($con)); 
} 

mysqli_select_db($con,"data"); 
$sql="SELECT * FROM tech_info WHERE Tech_Num = '".$q."'"; 

$result = mysqli_query($con,$sql); 

echo "<table border='1'> 
<tr> 
<th>First Name</th> 
<th>Last Name</th> 
<th>Tech Number</th> 
<th>Mobile Number</th> 
</tr>"; 

while($row = mysqli_fetch_array($result)) 
    { 
    echo "<tr>"; 
    echo "<td>" . $row['Tech_F_Name'] . "</td>"; 
    echo "<td>" . $row['Tech_L_Name'] . "</td>"; 
    echo "<td>" . $row['Tech_Num'] . "</td>"; 
    echo "<td>" . $row['Mobile_Num'] . "</td>"; 
    echo "</tr>"; 
    } 
echo "</table>"; 

mysqli_close($con); 
?> 
+3

提示:建議使用jQuery來處理AJAX請求。簡單得多。 – Raptor

+0

你應該調試'xmlhttp.readyState'。 AJAX調用是否成功? – Raptor

+1

1.你永遠不會獲得xmlhttp - 所以我懷疑它是未初始化的。 2.改用工具包。 3.如果你想避免瘋狂,不要使用jQuery。如果你是初學者,可以和Dojo一起去。 –

回答

0

這是更好地使用jQuery的替代JavaScript來ajax.Here是的jQuery代碼AJAX。 不要忘記在你的scirpt中添加js。

<script> 
function showUser(str) { 
var datastring ='?q='+str; 
$.ajax({ 
      type:'POST', 
      url : 'getuser.php' 
      data:datastring, 
      success:function(msg) 
      { 
       alert(msg); 
      } 
}); 
} 
</script>