IE8中的Ajax脚本失败

The following script executes and works fine in Safari, Chrome and Firefox - but not in IE8. Unfortunately IE8 is one of my targeted browsers so this is a bit of a problem. Since I don't have a lot of experience with Ajax I'm not really sure where to begin looking either.

I've noted that IE reports an error on line 15 (marked with **) which doesn't really make sense as the if-else should stop it from even looking at that line.

function getNames(str) {
    var xmlhttp;
    // Clear previous queries
    if(str.length == 0){
        document.getElementById("txtHint").innerHTML = "";
        return;
        // Due to the high number of possible hits we'll demand 3 chars
        // before we start querying.
    }else if(str.length < 3){
        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.status == 200 && xmlhttp.readyState == 4){
            // String from get_names.php is comma separated
            var arr = xmlhttp.responseText.split(",");
            // The UL list we want our names in
            var ul = document.getElementById("names");

            // Clear the list for each key in
            if(ul.hasChildNodes()){
                while(ul.childNodes.length >= 1){
                    ul.removeChild(ul.firstChild);
                }
            }
            // Step trough the String in Array form
            for(var i = 0; i < arr.length; i++){
                // :@ means that we've reached the end of applicable names.
                if (arr[i] != ":@") {
                    var li = document.createElement("li");
                    li.innerHTML = newListItem = arr[i];
                    // Inserts the current name into the list.
                    ul.insertBefore(li, ul.getElementsByTagName("li")[0]);
                }
            }
        }
    }
    xmlhttp.open("GET", "./ext/get_names.php?q=" + str, true);
    xmlhttp.send();
}

You should first check the readyState and then check the status. This is a common error that is reported but ignored in most browsers. I'm not sure that this is the solution to your problem, but since you haven't provided the error message, it's hard to help you further.

if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   // Code ...
}

As far as I know the 'window.XMLHttpRequest'-check should be ok.

You could try taking a look at this answer. In that case, the problem was that native xmlhttprequest was disabled in the browser settings.