开发者

about using ajax

I'm displaying the cotntent of a text file on web page(say between <div id='text'></text&开发者_如何学Gogt;) this file's content is edited by any user who view the page, I already use ajax to write to the file and display to the current user, but if there are any users browsing the page at the same moment they have to refreh the page to see the new edited content. I want to know how to use ajax to make the part that contain the file content remain updated continmuosly without refreshing the page

<script type='text/javascript'>
function change(){

    if (window.XMLHttpRequest)  xhr=new XMLHttpRequest();
    else      xhr=new ActiveXObject("Microsoft.XMLHTTP"); //IE5

    xhr.onreadystatechange=function()
      {
        if (xhr.readyState==4 && xhr.status==200)
        {
            if(xhr.responseText=="empty") return;
            document.getElementById("space").innerHTML=xhr.responseText;
        }
     }
    var str=document.getElementById('msg').value;
    document.getElementById("msg").value="";    
    xhr.open("GET","response.php?q="+str,true);
    xhr.send();           
}
</script>

<center>
<div id='space'>nothing</div>
<input type='text' name='msg' id='msg'>
<input type='button' onClick='change()' value='Click'>
</center>


The simplest way to accomplish the "server push" effect is through polling.

In your case, you can add this functionality by adding a simple Javascript statement:

window.onload = function()
{
    setInterval("change();", 5000);
};

This code will call change(); every 5000 ms.


You could use setInterval() to perform a periodic AJAX query to check for updates. Then, if needed,update the content on the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜