2013-07-28 25 views
0

我在PHP/jQuery/MySQL中創建了一個相對簡單的「創意板」。定期刷新div以檢查表中是否有新條目

在頁面加載div #chat拉取數據庫中的當前條目。

<div id="chat"> 
    <?php 

    $sql = "SELECT * from idea ORDER BY id DESC;"; 
    $result = $pdo->query($sql); 

    if($result->rowCount() > 0 && !empty($result)) 
    { 
     foreach ($result as $row) 
     { 
     $title = $row['title']; 
     $idea = $row['idea']; 

     echo '<span class="idea"><strong>' . $row['title'] . "</strong>&nbsp;-&nbsp;" . $row['idea'] . '&nbsp;<a class="delete" href="">[Delete]</a></span>'; 
     } 
    } 
    ?> 
    </div> 

但是我想它採用定期刷新:

<body onload="setInterval('chat.update()', 1000)"> 

下面的例子詳細介紹瞭如何它可以使用一個文本文件來完成,我怎麼會與查詢數據庫(這樣做該示例發現在http://css-tricks.com/jquery-php-chat/)?

//Updates the chat 
function updateChat() { 
    if(!instanse){ 
     instanse = true; 
     $.ajax({ 
      type: "POST", 
      url: "process.php", 
      data: {'function': 'update','state': state,'file': file}, 
      dataType: "json", 
      success: function(data) { 
       if(data.text){ 
        for (var i = 0; i < data.text.length; i++) { 
         $('#chat-area').append($(" 

         "+ data.text[i] +" 

         ")); 
        } 
       } 
       document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight; 
       instanse = false; 
       state = data.state; 
      } 
     }); 
    } 
    else { 
     setTimeout(updateChat, 1500); 
    } 
} 

我希望某些行被刪除,所以就被附加條目的頂部,我也喜歡一些被刪除。

它應該模擬實時對話。

+1

您可以在ajax請求的完整回調函數中設置超時時間 –

+0

@roasted您能告訴我一個例子嗎? – methuselah

+0

http://css-tricks.com/examples/Chat.zip從這裏下載文件 –

回答

2

您可以使用簡單的long polling技術來更新您的聊天。

如:

//Updates the chat 
function updateChat() { 
    if(!instanse){ 
     instanse = true; 
     $.ajax({ 
      type: "POST", 
      url: "process.php", 
      data: {'function': 'update','state': state,'file': file}, 
      dataType: "json", 
      success: function(data) { 
       if(data.text){ 
        for (var i = 0; i < data.text.length; i++) { 
         $('#chat-area').append($(" 

         "+ data.text[i] +" 

         ")); 
        } 
       } 
       document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight; 
       instanse = false; 
       state = data.state; 
      }, 
      complete: function(){ 
       setTimeout(
        updateChat, /* Request next message */ 
        10000 /* ..after 10 seconds */ 
       );     
      }, 
      error: function(XMLHttpRequest, textStatus, errorThrown){ 
       //display you error message    
      }, 
      timeout: 10000 //Timeout is necessary to prevent chaining of unsuccessful ajax request  
     }); 
    } 
} 
0

您可以使用socket.io庫來實現服務器到客戶端通知和/或雙向實時通信。