为什么这个ajax代码会延迟


Why this ajax code got delay?

我正在尝试制作搜索地址表单。

这就是结构和方法。

search_address.html:

<form id="search_address_form" onSubmit="sendAddress(); return false;">
    <input id="input_address" class="input_address" name="input_address" type="text" placeholder="example: blahblahblah"/>
</form>
<div id="addressList_layer" class="addressList_layer">
<script>
    input_address = document.getElementById('input_address');
    input_address.addEventListener('keydown',function(){    
       sendAddress();    
    });
    function sendAddress(){
        xhrDocOpen('./php/search_address.php?searchingFor='+inputAddress_data.value,'addressList_layer','get');
        return false;
    }
</script>

search_address.php:

<?php
include_once('./config.php');
extract($_GET);
echo ($searchingFor);
?>

此代码运行良好。

但它运行有点延迟。。。

我的意思是,例如,

input_address.value : "1"
addressList_layer.value : ""
input_address.value : "123"
addressList_layer.value : "12"
input_address.value : "123456"
addressList_layer.value : "12345"
input_address.value : "123abc"
addressList_layer.value : "123ab"

像这样,addressList_layer显示的总是比input_address延迟一步。

我不知道为什么。。。

有人能猜出这种情况的原因并给我解决方案吗?

ps。xhrDocOpen()是…

var xhr = new XMLHttpRequest();
function xhrDocOpen(doc,placeID,method){
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4 && xhr.status==200){
            document.getElementById(placeID).innerHTML=xhr.responseText;
        }
    xhr.open(method,doc,true);
    xhr.send('');
}

如果您试图使用"keydown"事件,这是常见的问题。

只要尝试将其更改为"keyup",它就会工作。