Ajax脚本在IE8中失败

Ajax script fails in IE8

本文关键字:失败 IE8 脚本 Ajax      更新时间:2023-09-26

以下脚本在Safari、Chrome和Firefox中执行良好,但在IE8中则不然。不幸的是,IE8是我的目标浏览器之一,所以这有点问题。由于我在Ajax方面没有太多经验,我也不确定从哪里开始寻找。

我注意到IE在第15行报告了一个错误(用**标记),这实际上没有意义,因为if else应该阻止它查看该行。

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();
}

您应该首先检查readyState和,然后检查状态。这是一个常见的错误,在大多数浏览器中都会报告但被忽略。我不确定这是否是你问题的解决方案,但由于你还没有提供错误消息,很难进一步帮助你。

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

据我所知,"window.XMLHttpRequest"-检查应该可以。

你可以试着看看这个答案。在这种情况下,问题是在浏览器设置中禁用了本机xmlhttprequest。