我们可以使用xmlhttp.open();在同一个文件中

时间:2014-07-18 10:48:20

标签: php ajax

我尝试使用w3school的这些代码,但是我遇到了一些问题。

我的第一个档案:

    <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","getresult.php?q="+str,true);
    xmlhttp.send();
    }
    </script>

  <?php
   echo "First name: <input type=\"text\" id=\"txt1\" onkeyup=\"showHint(this.value)\" />";
   echo "<p>Suggestions: <span id=\"txtHint\"></span></p>";
  ?>

我的第二个档案[getresult.php]:

<?php
  $a[]="Anna";
  $a[]="Brittany";
  $a[]="Cinderella";
  $a[]="Diana";

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

  // lookup all hints from array if $q is different from "" 
  if ($q !== "")
    { 
      foreach($a as $key=>$name)
        { 
          if ($q==$key)
          { 
            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个文件我应该如何处理

    xmlhttp.open("GET","getresult.php?q="+str,true);

因为我在我的服务器上传这两个文件它不起作用但我在我的电脑上运行时工作(localhost)

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用此

if (isset($_GET['q'])) {
    //getresult.php contents
}
else {
    //first file contents
}
相关问题