防止xmlhttp函数再次在keyup上运行

时间:2020-06-03 00:14:53

标签: javascript php mysql ajax xmlhttprequest

所以我有一个keyup函数,该函数从MySQL表中检索数据,然后显示它。但是,如果更改了字母,它将再次检索数据。

参见下图 How it currently isIn the inspector

它应该做的只是将这些建议替换为新建议,而不是将其添加到列表中

编辑:Shoeaeb的解决方案有效,但不像他建议的那样。

document.getElementById('schoolListMenu').innerHTML="";

我在调用keyup函数之后立即添加了该行。一旦用户停止键入,这将清除div中的内容并将其替换为更新的内容。如果用户再次按下某个键,它将再次清除div并追加更新后的结果。

edit2:更新了JS代码

var timeout = null;
function getSchool(schoolType){
    if(schoolType1.classList.contains('active') || schoolType2.classList.contains('active'))
    {
        schoolNameField.onkeyup = function(e)
        {
            document.getElementById('schoolListMenu').innerHTML="";
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                var query = e.target.value;
                console.log(query);
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function() {
                    if (this.readyState === 4 && this.status === 200) {
                        var schoolResult = this.responseText;
                        schoolResult = schoolResult.split("|");
                        for(var i = 0; i < schoolResult.length; i++)
                        {
                            var schoolSuggestion = document.createElement('div');
                            schoolSuggestion.id = 'schoolSuggestion'+i;
                            schoolSuggestion.className = 'item';
                            schoolSuggestion.innerText = schoolResult[i];
                            document.getElementById('schoolListMenu').appendChild(schoolSuggestion);
                        }
                    }
                };
                xmlhttp.open("GET", "scripts/schoolLookup.php?type="+schoolType+"&name="+query, true);
                xmlhttp.send();
            }, 500);
        };
    }
}

如何获取替换内容而不是添加新div的信息?我觉得我了解问题所在,知道解决方案是什么,但我不能一言不发

1 个答案:

答案 0 :(得分:0)

更改此行

document.getElementById('schoolListMenu')。appendChild(schoolSuggestion);

document.getElementById('schoolListMenu')。innerHTML(schoolSuggestion);

或者您可以在添加前清除列表

document.getElementById('schoolListMenu')。innerHTML =“”; document.getElementById('schoolListMenu')。appendChild(schoolSuggestion);