weixin_33739523 2018-05-24 02:11 采纳率: 0%
浏览 59

未触发onchange方法

    <html>
     <head>
      <script>
       function showUser(str) {
       if (str == "") {
         document.getElementById("txtHint").innerHTML = "";
         return;
       } else { 
        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 (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>

    <form>
     <select name="users" onchange="showUser(this.value)">
     <option value="">Select a person:</option>
     <option value="1">Peter Griffin</option>
     <option value="2">Lois Griffin</option>
     <option value="3">Joseph Swanson</option>
     <option value="4">Glenn Quagmire</option>
     </select>
    </form>
     <br>
     <div id="txtHint"><b>Person info will be listed here...</b></div>

    </body>
    </html>

The page shows the dropdown list. However, it seems the onchange method is not triggered. I don't get any return from the php. The php code is here. https://www.w3schools.com/php/php_ajax_database.asp

</div>
  • 写回答

2条回答 默认 最新

  • weixin_33709219 2018-05-24 02:23
    关注

    It seems to be working for me. Are you running this html file off your local machine? What I mean is that when you are loading this html file on your browser, does the address bar read file://<path_to_html> or http(s)://<path_to_html>?

    If it is the former, then you need to provide the full path to the server that's hosting the getuser.php.

    When I tried your code (running the html off my local machine), the onchange event was being triggered and the xmlhttp object was being created but no http request was being sent to the server (as per what I saw on by browser's dev tools). Then I realized I had to change the location of the getuser.php because it needed to be hosted on a server.

    评论

报告相同问题?