AJAX代码两次发送GET请求

时间:2014-01-19 23:07:14

标签: javascript php ajax

我的TA说,遵循AJAX代码的GET请求正在发送两次。但我不知道我怎么也能解决它。如何处理这个问题的一般方法是什么?

这是一个简单的页面,带有搜索框,可在您输入时提供建议。问题必须出在getByPrefix函数中。

JS代码:

function set(arg)
{
    var searchtext = document.getElementById("searchtext");
    searchtext.value = arg.innerHTML;
    showMatches(searchtext);
}

function getByPrefix(prefix, callback)
{
    var prefixes = [];

    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            var response = JSON.parse(xmlhttp.responseText);

            for (var i = 0; i < response.length; i++) // prepsani do jednoducheho indexovaneho pole
            {
                prefixes.push(response[i].drug);
            }

            callback(prefixes);         
        }
    }

    xmlhttp.open("GET","prefixes.php?q="+prefix,true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
    xmlhttp.setRequestHeader('Cache-Control', 'no-cache');
    xmlhttp.send();
}

function action2(text)
{
    getByPrefix(text.value, showMatches);
}

function showMatches(text)
{
    var matches = text;

    var form = document.getElementById("search");
    var results = document.getElementById("results");

    if (results != null)
        form.removeChild(results);

    var div = document.createElement("div");
    div.id = "results";

    for (var i =0; i < matches.length; i++)
    {
        var p = document.createElement("p");
        p.className = "hidden";
        p.onclick =  (function(a) { return function(){ set(a); }})(p);
        p.innerHTML = matches[i];

        div.appendChild(p);
    }

    if (matches.length>1 && text.value != "")
        form.appendChild(div);

    if (matches.length==1 && text.value != matches[0])
        form.appendChild(div);
}

PHP代码:

<?php
function head()
{
    global $db;
?>
<head>
    <title>Search</title>
    <?php head_common(); ?>
    <script type="text/javascript" src="js/main.js"></script>
</head>
<?php
}

function body()
{
?>
<body>
    <?php heading(); ?>
   <div>
    <img src="img/logo.jpg" height="200" width="400"> 
    <form id="search" method="get" action="index.php">
        <p>
            <input name="page" value="results" type="hidden">
            <input name="part" value="1" type="hidden">
            <input name="hledej" id="searchtext" autocomplete="off" onKeyUp="action2(this)" type="text">
            <button>Hledej</button>
        </p>
    </form>
    </div>
    <?php footer(); ?>
</body>
<?php
}
?>

1 个答案:

答案 0 :(得分:2)

您可能使用SHIFT键输入大写字母,因此一旦释放密钥,keyup事件将被触发两次,您有2 AJAX个请求。

您可以使用eventData参数过滤按下的键。对于SHIFT键看here

相关问题