我正在尝试理解并将Ajax功能应用于我的网站。但我面临一些问题,我需要一些解释。这是我从w3school.com获得的代码: -
<!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;
?>
但我有以下问题:
str.length==0
?因为我认为应该是
fname.length==0
q="+str in "gethint.php?q="+str
部分的用途是什么?$q=$_REQUEST["q"]
?因为我认为应该是
$q=$_REQUEST["fname"]
答案 0 :(得分:1)
1:str.length == 0将检查输入的字符串是否应至少为1个字符长或不为空。 2:q =“+ str”在gething.php中?q =“+ str”---这意味着一旦你从这个url输入任何一个字符,它将通过传递(追加)str作为参数在数据库中开始查找输入的字符的网址。 3:$ q = $ _ REQUEST [“q”] ..会将 url 中传递的值作为参数。
希望这会对你有所帮助。
答案 1 :(得分:0)
str.length == 0?它是可选的。如果你觉得它有需要,那么使用它中止。实际上这是用于向innerHTML显示结果
q =&#34; + str in&#34; gethint.php?q =&#34; + str part? bcz xmlhttp.open(&#34; GET&#34;,&#34; gethint.php?q =&#34; + str,true);在这个xmlhttp.open中,在两个方法中传递变量,如GET或POST 所以它需要传递存储完整数据的变量,如q从这里传递值并使用xmlhttp.send()显示结果;
答案 2 :(得分:-3)
SCRIPT中使用的函数名是&#34; showHint&#34;它以id =&#34; txt1&#34;的形式传递所以这里&#34; THIS.VALUE&#34;允许参数从名为&#34; fname&#34;的字段中获取值。这就是我们使用str.length == 0而不是fname.length == 0。
的原因我希望你能理解我想要解释的内容。注意参数和 THIS.VALUE