为什么必须不断刷新“ ajaxLoad.php”才能让消息实时?

我用jquery和AJAX编写了一个简单的聊天脚本,但是其中存在一个巨大漏洞:我只能与自己聊天...... 这是我的javascript代码:

<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js"  type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function(){

$("#status").load('ajaxLoad.php');
$("#userArea").submit(function(){
    var hr = new XMLHttpRequest();
var id = '<?php echo $id; ?>';
var name = '<?php echo $name; ?>';


var url = "ajaxPost.php";
var msg = document.getElementById("messages").value;


 var vars = "messages="+msg+"&id="+id+"&name="+name;
hr.open("POST", url, true);

hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        $("#status").append(return_data);
    }
}
hr.send(vars);
return false;});
 });

这是第二个文件“ ajaxLoad.php”:

<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT messages,id FROM chat");
while($row = mysql_fetch_array($sql))
    {

echo $row["messages"];


    }
    ?>

我需要不断刷新“ ajaxLoad.php”,才能让用户可以实时聊天而无需刷新页面...对此有何解决办法?

You can use javascript setInterval to call your php script every x seconds.

https://developer.mozilla.org/en/window.setInterval

// reload every second
setInterval(function() {
  $("#status").load('ajaxLoad.php');
}, 1000);

Be careful of making too requests to the server. It's going to be rather intensive.

If you want to get bleeding edge, you should look into WebSockets.