为什么在导航到同一站点的不同页面后,Ajax自动完成框会停止工作?


Why would an Ajax Auto-Complete box stops working after navigating to a different page on the same site?

我在一个网站上工作,有一个自动完成搜索框。搜索框依赖于Ajax、Javascript和PHP。用户开始在搜索框中输入,一个ajax请求调用一个php文件,该文件轮询数据库并返回可能的结果。这似乎工作得很好,直到用户导航到网站上的不同页面,然后返回到搜索页面。一旦您返回到搜索页面并尝试新的搜索,自动完成功能就不会起任何作用。但是,如果您导航到外部页面(例如Google)并返回到搜索页面,它会再次工作。

我不确定这是否与正在发生的某种缓存或绑定有关,或者是否在代码中有我实际做错的东西。

搜索页面相关代码:

<script>
    var tax = document.getElementById("taxonomic");
    var sea = document.getElementById("searchDiv");
    var ctt = "";
function updateSearch(str, field)
{
    str = str.split(",");
    str = str.pop();
    str = str.trim();
    if(field == 1)
    {
        if (window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest();
        }
        else
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                  document.getElementById("resultsSpecies").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST","http://.../UpdateSpecies.php?str="+str,true);
        xmlhttp.send();
    }
    if(document.getElementById('taxonomic').value.length > 0)
    {
        document.getElementById('submitDiv').style.display= 'inline';
        document.getElementById('searchDiv').style.display= 'inline';
    }
    else
    {
        document.getElementById('submitDiv').style.display= 'none';
        document.getElementById('searchDiv').style.display= 'none';
    }
}
</script>
<input name="species" class="form-control" id="taxonomic" placeholder="Taxonomic    Information" onfocus="updateSearch(this.value, 1)" onkeyup="updateSearch(this.value, 1)">
<div id="resultsSpecies" class="results"></div>

Ajax请求调用的PHP页面(UpdateSpecies.php)中的相关代码:

<?php
$str=$_REQUEST["str"];
$con=mysqli_connect();
if
    echo ...
else
    echo ....
mysqli_close($con);

听起来可能有一个'onchange'事件执行Ajax调用,它只在一种特定情况下被添加到DOM中。

使用Javascript控制台运行时,我发现以下错误:

请求的资源上没有'Access-Control-Allow-Origin'标头。

将以下代码行添加到UpdateSpecies.php中解决了这个问题。

header('Access-Control-Allow-Origin: (your_url));

谢谢你的建议,我认为这更可能是一个PHP错误而不是Javascript。