如何调试我的ajax建议代码不起作用?

时间:2017-07-20 07:28:47

标签: php ajax

这是我的 ajax.php 代码,用于从存储某些名称的数组中获取建议。它没有用我的代码中有什么问题

<html>
   <head>        
      <script type="text/javascript" >
         function showHint(str) {
            if (str.length == 0) {
                document.getElementById("txtHint").innerHTML = "";
                return;
            } else {
                if (window.XMLHttpRequest) {

                    var xmlhttp = new XMLHttpRequest();
                } else {
                    xmlhttp = new ActivexObject("Microsoft.XMLHTTP");
                }
                alert(hi);
                xmlhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        document.getElementById("txtHint").innerHTML = 
                                                  this.responseText;
                    }
                };
                xmlhttp.open("GET", "getuser.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)">
    </form>
    <p>Suggestions: <span id="txtHint"></span></p>
 </body>

这是我的 getuser.php 代码,其中存储了一些名称请查看我的代码给我建议

 // Array with names
  $a[] = array('jani','baji','rabbani','jagadish',
             'bapeswar','rizwan','rahamtulla','moha
             n','sagar','rakul');

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

$hint = "";

// lookup all hints from array if $q is different from "" 
if ($q !== "") {
$q = strtolower($q);
$len = strlen($q);
foreach ($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
        if ($hint === "") {
            $hint = $name;
        } else {
            $hint .= ", $name";
        }
    }
 }
}    
// Output "no suggestion" if no hint was found or output correct values 
echo $hint === "" ? "no suggestion" : $hint;

1 个答案:

答案 0 :(得分:0)

怎么样

    1. Install xdebug, and debug your php code
    2. check network tab in browser dev tools and check php code output
    3. do this


if (this.readyState == 4 && this.status == 200) {
                        document.getElementById("txtHint").innerHTML = 
                                                  this.responseText;
} else {
     console.log(this.readyState, this.status);
}