0

我正在尝试创建一个与我的数据库通信的动态 AJAX 搜索栏。这是我的代码。

function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
    return new XMLHttpRequest();
}
else if (window.ActiveXObject){
    return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
    alert("Your browser does not support our dynamic search");
}
}

var search = getXmlHttpRequestObject();

function ajaxSearch(){
    if (search.readyState == 4 || search.readyState == 0){
        var str = escape(document.getElementById('searchBox').value);
        search.open("GET", 'searchSuggest.php?search=' + str, true);
        search.onreadystatechange.handleSearchSuggest;
        search.send(null);
    }
}

function handleSearchSuggest(){
    if(search.readyState == 4){
        var ss = document.getElementById('ajaxSearch');
        ss.innerHTML = '';
        var str = search.responseText.split("\n");
        for(i=0; i<str.length-1; i++){
            var suggestion = '<div onmouseover="javascript:suggestOver(this);"';
            suggestion += 'onmouseout="javascript.suggestOut(this);"';
            suggestion += 'onclick="javascript:setSearch(this.innerHTML);"';
            suggestion += 'class="suggestLink">' + str[i] + '<div>';
            ss.innerHTML += suggestion;
        }
    }
}

function suggestOver(divValue){
    divValue.className = "suggestLink";
}

function suggestOut(divValue){
    divValue.className = "suggestLink";
}

function setSearch(x){
    document.getElementById('searchBox').value = x;
    document.getElementById('ajaxSearch').innerHTML = '';
}

问题是 readyState 从 0 变为 1,但随后它不会变为任何其他状态。我需要将其更改为 4 才能输入函数handleSearchSuggest()。我也在控制台中收到此错误: TypeError: search.onreadystatechange is null

4

2 回答 2

1

您需要正确设置回调函数。

search.onreadystatechange = handleSearchSuggest;

请注意,就绪状态 1 表示OPENED4 表示DONE。您可以通过类的属性对此进行测试XMLHttpRequest

XMLHttpRequest.UNSENT == 0
XMLHttpRequest.OPENED == 1
XMLHttpRequest.HEADERS_RECEIVED == 2
XMLHttpRequest.LOADING == 3
XMLHttpRequest.DONE == 4
于 2014-12-08T15:23:26.610 回答
0

尝试:

search.onreadystatechange = handleSearchSuggest;    
于 2014-12-08T15:22:59.940 回答