我是编程新手,也是我第一次使用PHP学习AJAX。 我从互联网上获得了一个可用的示例代码并对其进行了研究,但有一些我不理解的代码,我真的很沮丧。
在index.php
中,我对代码xmlhttp.open("GET","gethint.php?q="+str,true);
感到困惑。我不知道q
代表什么。据我所知,q
应该代表一个名为q
的html元素。例如,我有<input type="text" name="q" />
,然后我知道我有一个文本框名称q
。但在此示例中,我找不到任何名为q
的元素。请帮忙......
index.php
<html>
<head>
<script type="text/javascript">
function showHint(str)
{
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>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
gethint.php
<?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=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
答案 0 :(得分:4)
在您的示例中,q
是传递给gethint.php的参数,其值包含在变量str
中。
只要按下并释放键(onkeyup
事件),变量就会从“名字”输入元素中获取其值。
然后在行q
行的PHP文件中访问$q=$_GET["q"];
的值。
您可以根据需要命名传递给PHP页面的参数,它们不需要与HTML元素对应。
答案 1 :(得分:1)
q
是HTTP GET请求的参数名称:
答案 2 :(得分:1)
它的LIKE A URL参数类似于
PHP中,
gethint.php?q=mYstring
echo $_GET['q'];// output as mYstring
在js中,
var str ='mYstring';
"gethint.php?q="+str
echo $_GET['q'];// output as mYstring
如果发生任何问题,我可以得到添加评论.. (经常这样做)