2014-04-19 17 views
0

我想了解並將Ajax功能應用到我的網站。但我面臨一些問題,我需要一些解釋。下面是我從w3school.com:-隨着用戶開始輸入PHP Ajax showhints

<!DOCTYPE html> 
<html> 
<head> 
<script> 
function showHint(str) 
{ 
var xmlhttp; 
if (str.length==0) 
    { 
    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","gethint.php?q="+str,true); 
xmlhttp.send(); 
} 
</script> 
</head> 
<body> 

<h3>Start typing a name in the input field below:</h3> 
<form action=""> 
First name: <input type="text" name="fname" id="txt1" onkeyup="showHint(this.value)" /> 
</form> 
<p>Suggestions: <span id="txtHint"></span></p> 

</body> 
</html> 

// and here is gethint.php code 

<?php 
// Fill up array with names 
$a[]="Anna"; 
$a[]="Brittany"; 
$a[]="Cinderella"; 
$a[]="Diana"; 
$a[]="Eva"; 
$a[]="Fiona"; 
$a[]="Gunda"; 
$a[]="Hege"; 
$a[]="Inga"; 
$a[]="Johanna"; 
$a[]="Kitty"; 
$a[]="Linda"; 
$a[]="Nina"; 
$a[]="Ophelia"; 
$a[]="Petunia"; 
$a[]="Amanda"; 
$a[]="Raquel"; 
$a[]="Cindy"; 
$a[]="Doris"; 
$a[]="Eve"; 
$a[]="Evita"; 
$a[]="Sunniva"; 
$a[]="Tove"; 
$a[]="Unni"; 
$a[]="Violet"; 
$a[]="Liza"; 
$a[]="Elizabeth"; 
$a[]="Ellen"; 
$a[]="Wenche"; 
$a[]="Vicky"; 

// get the q parameter from URL 
$q=$_REQUEST["q"]; $hint=""; 

// lookup all hints from array if $q is different from "" 
if ($q !== "") 
    { $q=strtolower($q); $len=strlen($q); 
    foreach($a as $name) 
    { if (stristr($q, substr($name,0,$len))) 
     { if ($hint==="") 
     { $hint=$name; } 
     else 
     { $hint .= ", $name"; } 
     } 
    } 
    } 

// Output "no suggestion" if no hint were found 
// or output the correct values 
echo $hint==="" ? "no suggestion" : $hint; 
?> 

得到一個代碼,但我有以下問題:

  1. 爲什麼我們使用str.length == 0?因爲我認爲這應該是 fname.length == 0
  2. 什麼用的q =「+ STR在 」gethint.php?Q =「 + STR一部分?
  3. 爲什麼我們使用$ Q = $ _ REQUEST [ 「q」],因爲我認爲這應該是 $ q = $ _ REQUEST [ 「FNAME」]

請回答這三個問題的幫助,我將不勝感激任何進一步的解釋

回答

0

1?: str.length == 0將檢查輸入的字符串是否應該至少有1個字符長或不爲空 2:q =「+ str」in gething.php?q =「+ str」---這意味着一旦你進入y字符,它將開始在數據庫中查看輸入的字符,方法是將(str)(str)作爲參數傳遞給url。 3:$ q = $ _ REQUEST [「q」] ..將獲得url作爲參數傳遞的值。

希望這會幫助你。

0

str.length == 0?其可選。如果你覺得有需要的話,那就用它來實現,實際上這是爲了向innerHTML顯示結果。「#」 「,」gethint.php?q =「+ str,true);在這個xmlhttp.open中,通過兩個方法(如GET或POST)傳遞變量 因此它需要傳遞變量,其中存儲所有數據,如q該值並通過使用xmlhttp.send()顯示結果;