0

我正在使用 html 进行实时搜索,
我工作得很好,但我遇到了一个小问题,这是我的索引代码:

<form id="quick-search" action="livesearch.php" method="GET" >
<p>
Search:
<input id="qsearch" type="text" name="qsearch" onkeyup="liveSearch()" />
<input type="submit" />
</p>
<div id="searchResults">

</div>
</form>

这是我的js代码:

function liveSearch()
{
    var url = "livesearch.php";
    var s = document.getElementById('qsearch').value;
    http.open("POST", "livesearch.php?qsearch="+s, true);
    http.onreadystatechange = function() 
    {
        if(http.readyState == 4 && http.status == 200) 
        {
            document.getElementById('searchResults').innerHTML = 'Suggestions are as follow'+http.responseText; 
            //alert(http.responseText);
        } 
    }

    http.send();
}

我得到了正确的结果,但是当我清空完整的输入框时,我会从数据库中获取完整的列表框,在清空输入框时,我想清除列表框

4

1 回答 1

0

您应该在 PHP 和用户端保护您的代码。为此,请检查用户发送了多少封信:if(s.length < 2 )return; 防止 AJAX 请求

function liveSearch()
    {
    var url = "livesearch.php";
    var s = document.getElementById('qsearch').value;
    if(s.length < 2) return; // here You escape if there isn't enough letters to search
    http.open("POST", "livesearch.php?qsearch="+s, true);
    http.onreadystatechange = function() 
    {
        if(http.readyState == 4 && http.status == 200) 
        {
            document.getElementById('searchResults').innerHTML = 'Suggestions are as follow'+http.responseText; 
            //alert(http.responseText);
        } 
    }

    http.send();
}

但请记住也要在 PHP 上保护它:

if(count($_REQUEST['qsearch']) < 2) return false;
于 2013-01-11T08:22:55.297 回答