doumu1873
2016-11-15 23:26
浏览 58
已采纳

未捕获的ReferenceError:xmlhttp未定义?

<html>
<head>
    <title>List</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Javascript code -->
<script>
         function showUser(str) {
         if (str == " ") {
         document.getElementById("txtHint").innerHTML = " ";
         return;
         } else {
         if (window.XMLHttpRequest) {
         // code for IE7+, Firefox, Chrome, Opera, Safari
         } 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>
        <!-- CSS for HTML table -->
<style>
    table {
    width: 100%;
    border-collapse: collapse;
    }

    table, td, th {
    border: 1px solid black;
    padding: 5px;
    }

    th {text-align: left;
    }
</style>

</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>
    <div id="txtHint">Result from PHP script should appear here</div>
 </body>
 </html>

When I run the following HTML page in the Google Chrome Browser via Netbeans, I am met with this error (see Title) when I try to select a person from the list.

xmlhttp.onreadystatechange = function()

This line of code and the one below seems to be the areas of concern based on Chrome's Developer tools.

select name="users" onchange="showUser(this.value)

Can anyone pinpoint what needs to be changed?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxian1895 2016-11-15 23:35
    已采纳

    Right underneath:

    // code for IE7+, Firefox, Chrome, Opera, Safari
    

    Add:

    xmlhttp = new XmlHttpRequest();

    That way, you'll satisfy web browsers with javascript engines that have XMLHttpRequest defined.

    Also, xmlhttp needs to have a valid value (handle) before "xmlhttp.onreadystatechange = function()" can be properly executed.

    If your browser (especially very old IE browsers) is still picky then change "xmlhttp" to "var xmlhttp" since var before a variable name means define a new variable.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题