gpt4 book ai didi

php - 第一次接触AJAX,有几行代码看不懂

转载 作者:可可西里 更新时间:2023-11-01 00:36:31 25 4
gpt4 key购买 nike

我是编程新手,这是我第一次使用 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;
?>

最佳答案

在您的示例中,q 是传递给 gethint.php 的参数,其值包含在变量 str 中。

每当按下和释放一个键(onkeyup 事件)时,变量从“名字”输入元素获取其值。

然后 $q=$_GET["q"]; 在 PHP 文件中访问 q 的值。

您可以随意命名传递给 PHP 页面的参数,它们不需要与 HTML 元素相对应。

关于php - 第一次接触AJAX,有几行代码看不懂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6291442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com