2012-02-21 27 views
1

我正在嘗試構建一個簡單的聊天系統,但我不確定需要做什麼才能提交我的消息,該消息會在不同的計算機瀏覽器上更新。如何使用jquery和php自動更新簡單的feed/chat?

現在,當我提交消息時,它通過ajax調用將其存儲在數據庫中,同時我將該消息顯示在聊天中。

有什麼想法?

感謝

+1

看到這個答案,以一個非常類似的問題:http://stackoverflow.com/questions/9363572/php-reload-chat-box/9363721#9363721 – Basti 2012-02-21 17:59:59

回答

0

您需要輪詢服務器,並更新了一些間隔,看看setInterval()函數。只需更新每個聽衆的新聊天數據,就足以滿足您的需求。

1

您必須在特定時間間隔檢查服務器以獲取更新。你可以使用setInterval()函數。

下面是一個簡單的例子,它在名爲chatdiv的div的innerhtml中每隔3秒更新聊天消息。

您必須將chatid存儲在名爲chatid的隱藏字段中。

function updateRow() 
{ 
    chatid = $("#chatid").val(); //hidden field which contains the current chat id. 
    $.ajax({ 
     type: "POST", 
     url: "update.php", 
     data: {"chatid":chatid}, 
     success: function (output) { 
      $('#chatdiv').html(output); //updates the output to a div 
     } 
    }); 
} 
setInterval("updateRow()",3000); //call updateRow() function every 3 seconds. 

在update.php中,您可以從數據庫獲取聊天消息並對其進行回顯。 例如,

$id = $_POST['chatid']; 
$msg = $dbcon->queryUniqueValue("select message from chat where id=$id"); 
echo $msg;