2012-08-12 93 views
0

我從來沒有使用ajax,並且試圖完全理解這個例子,它與我想要做的類似。這裏是我關於示例代碼的問題。AJAX使用php和javascript連接到db

  1. 是否需要包含某種類型的ajax頭文件才能使用它?

  2. 這是什麼做的一部分在HTML文件中:

    • xmlhttp.open("GET","getuser.php?q="+str,true);
    • xmlhttp.send();
  3. 這是我最大的問題。什麼是q?它是否是前例: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); 
?> 

回答

1
  1. 不,這是在EMCAScript標準規範。
  2. 該特定的代碼行打開GET請求到getuser.php文件,在GET中傳遞GET參數q作爲str的值。
  3. 在該特定情況下,$ q被設置爲GETq的值。

簡而言之,您的JS調用一個PHP腳本來執行自己,同時將一個變量傳遞給(表面上)修改腳本的結果。

如果你不明白GETPOST變量,我建議閱讀至少the PHP manual's page on the $_GET array,或a more general overview of GET and POST variables

+0

謝謝。所以'q'是'str'是什麼值?所以q和str可以是1,2,3,4,5例如?? – 2012-08-12 01:53:51

+0

在這個特定的腳本中,'str'將等同於當前設置的表單項的'value'屬性。 – esqew 2012-08-12 01:55:02

0
xmlhttp.open("GET","getuser.php?q="+str,true); 
xmlhttp.send(); 

這將打開文件,然後將該URL發送到getuser.php。基礎知識:P

$q=$_GET["q"]; 

這就是ajax文件發送到您的getuser.php文件的內容。這不應該是一個「安全」變量,因爲get很容易被破解。如果需要,請嘗試使用帖子。

希望我幫助:)

+0

謝謝。我還有其他問題。那麼什麼是'q'值的例子? q是什麼值'str'是? – 2012-08-12 01:50:56

+0

q將是任何str等於。 – AlanPHP 2012-08-12 01:53:47