当我输入文本框时,我的Ajax调用不起作用

问题描述:

<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 == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();
    }
</script>


<form>
    First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
</form>
<span id="txtHint"></span>
-------------------------------------


<?php

$a[]="Anna";
$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[$a],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;
?>

Try changing this line

if (strtolower($q)==strtolower(substr($a[$a],0,strlen($q))))

to

if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))

<form>
    FirstN<input type="text" onkeyup="return showHint(this.value);" size="20" />
</form>

if (xmlhttp == 4 && xmlhttp.status == 200) {
Should BE
if (xmlhttp.readyState==4 && xmlhttp.status==200)

---------------------------

if (strtolower($q)==strtolower(substr($a[$a],0,strlen($q))))
Should BE
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))

I think that the error will occur on

strtolower(substr($a[$a],0,strlen($q))))

Here what is $a[$a] ..? Are like to executing for loop Then

  for($i=0; $i<count($a); $i++)
    {
     if (strtolower($q)==strtolower(substr($a[$a],0,strlen($q))))

please change like this

  for($i=0; $i<count($a); $i++)
    {
     if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))

$a replace with $i then only the $a[] is working