mongoDB、ajax、php只显示新消息


mongoDB, ajax, php to only display new messages

这可能是一个愚蠢的问题,但我认为它对所有新的mongoDB用户都有用,而不仅仅是我自己。

我目前正在编写一个实时聊天脚本,作为了解mongoDB的一种方式。我很难只在聊天中加载新消息,而不是加载所有消息并替换旧消息。这就是我所拥有的。

我的PHP:

try 
{
    $m = new Mongo(); // connect
    $db = $m->selectDB("local");
}
catch ( MongoConnectionException $e ) 
{
    echo '<p>Couldn''t connect to mongodb, is the "mongo" process running?</p>';
    exit();
}
$collection = $db->selectCollection("message");
echo "".$collection." selected";
$cursor = $collection->find();
// iterate cursor to display title of documents
foreach ($cursor as $document) {
echo $document["sender"].": ". $document["message"] . "<br>";

我的JS:

function get_new(){
    var messages = $.ajax({
        type: "POST",
        url: "ajax/receive.php",
        async: false
    }).success(function(){
        setTimeout(function(){get_new();}, 10000);
    }).responseText;
    $('div.messages').html(messages);
    }

我的消息集合:

"createdAt" => $now, 
"sender" => $sender, 
"message" => $message

我知道我的JS最终会开始使用.append(messages),但我真的不知道该怎么处理我的PHP。那么,我如何更改我的php以只查找新消息(比上一组消息旧的)

找到了答案。使用会话存储上次更新的时间。因此,PHP代码将如下所示:

$now = date("Y-m-d H:i:s");
$last = $_SESSION["last_message_ts"];
$session_last = new MongoDate(strtotime($last));
$session_now = new MongoDate(strtotime($now));
$_SESSION["last_message_ts"]=$now;
 try 
    {
        $m = new Mongo(); // connect
        $db = $m->selectDB("local");
    }
    catch ( MongoConnectionException $e ) 
    {
        echo '<p>Couldn''t connect to mongodb, is the "mongo" process running?</p>';
        exit();
    }
    $collection = $db->selectCollection("message");
    $cursor = $collection->find(array("createdAt" => array('$gt' => $session_last, '$lte' => $session_now)));
    // iterate cursor to display title of documents
    foreach ($cursor as $document) {
    echo $document["sender"].": ". $document["message"];
}