XMLHttpRequest中断键入文本字段

时间:2014-04-09 14:04:47

标签: javascript ajax xmlhttprequest

我使用XMLHttpRequest编写了一个小型聊天应用程序。 调用这3行会打断输入。

xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://mydomain.com/chat?action=getLatestEntries&latestID="+latestID, false);
xmlhttp.send(null);

如果用户在文本字段中键入内容,则XMLHttpRequest调用将中断键入1或2秒。

知道如何解决这个问题吗?

完整代码如下所示:

<script type="text/javascript">
var latestID = 0; // global
//This function will display the messages
function showmessages(){
   //Send an XMLHttpRequest 
   if(window.XMLHttpRequest){
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET","http://mydomain.com/chat?action=getLatestEntries&latestID="+latestID, false);
      xmlhttp.send(null);
   }
   else{
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      xmlhttp.open("GET","http://mydomain.com/chat?action=getLatestEntries&latestID="+latestID, false);
      xmlhttp.send();
   }   
   //Replace the content of the messages with the response from the .py file
   elem_messages = document.getElementById("messages");
   if (elem_messages) {
     elem_messages.innerHTML = xmlhttp.responseText;
   }

   // put scrollbar to bottom   
   elem_chat = document.getElementById("chat");
   if (elem_chat) {   
     elem_chat.scrollTop = document.getElementById("scroll_down").offsetTop + 5000;        
   } 
   //Repeat the function each 5 seconds
   setTimeout('showmessages()',5000);
}
//Start the showmessages() function
showmessages();
//This function will submit the message
</script>


<div id="chat" style="height: 450px; overflow: auto; width: 700px;">
    <div id="messages"></div>    
    <span id="scroll_down" />      
</div>

<div id="write">
    <form name="chatform" id="chatform" method="post" action="" onsubmit="send();return false"
          style="margin-top: 10px;">
        <p>Message:</p>
        <input type="text" id="message" size="90" /><br/>
        <div style="margin-top:6px"><input type="button" value="Send" onClick="send();" /></div>        
    </form>
</div>

注意:此处未列出send()函数,以保持帖子小而干净。

1 个答案:

答案 0 :(得分:1)

这是因为您正在使用锁定浏览器的同步请求。您需要将其更改为异步请求。