繁体   English   中英

第一次到 AJAX,不明白一些代码行

[英]1st Time to AJAX, Don't understand some line of codes

我是编程新手,这是我第一次学习 AJAX 和 PHP。 我从互联网上获得了一个工作示例代码并对其进行了研究,但是有些代码我不明白,我真的很沮丧。

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 元素。

q是 HTTP GET 请求的参数名称:

Hypertext_Transfer_Protocol#Request_methods

它的 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

如果有任何问题可以添加评论..pal(总是这样做)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM