2013-03-01 47 views
0

我已經實現了一個聊天系統使用彗星技術。這裏是鏈接(請參閱使用ajax的第二種方法)comet with ajaxCOMET與經典的AJAX聊天

當我用一個帳戶發送消息時,另一個接收方用自己的名稱接收它,我在2個瀏覽器和2個帳戶中使用它。 下面是代碼:

handleResponse: function(response) 
{ 

$('chat_id_box').innerHTML += '<u class="myId">' + response['name'] + '</u>:&nbsp;&nbsp;<p class="talk">' + response['msg'] + '</p></br>'; 

}, 

這裏S控制器

$filename = dirname(__FILE__).'./data.txt'; 
    $name = $this->session->userdata('name'); 
// store new message in the file 
    $msg = isset($_GET['msg']) ? $_GET['msg'] : ''; 
    if ($msg != '') 
    { 
    file_put_contents($filename,$msg.$name); 
    die(); 
    } 


    // infinite loop until the data file is not modified 
    $lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0; 
    $currentmodif = filemtime($filename); 
    while ($currentmodif <= $lastmodif) // check if the data file has been modified 
    { 
    usleep(10000); // sleep 10ms to unload the CPU 
    clearstatcache(); 
    $currentmodif = filemtime($filename); 
    } 

    // return a json array 
    $response = array(); 
    $response['msg']  = file_get_contents($filename); 
    $response['name']   = file_get_contents($filename); 
    $response['timestamp'] = $currentmodif; 
    echo json_encode($response); 
    flush(); 

想,如果我輸入XYZ:HELO世界!然後在第二個瀏覽器中,我收到此消息爲abc:helo world!abcxyz有2個用戶。代碼中有什麼問題?我無法理解。 謝謝..

+0

燦你發佈完整的代碼?我們需要充分理解您的代碼才能回答您的問題。 – Licson 2013-03-01 14:34:59

+0

是的,我有郵政編碼 – 2013-03-01 14:44:54

回答

1

您使用當前用戶的會話數據作爲名稱,但發件人實際上不是當前用戶。也許你可以將用戶名和消息一起發送到服務器?

handleResponse: function(response) 
{ 
    $('chat_id_box').innerHTML += '<u class="myId">'+response.user+'</u>:&nbsp;&nbsp;<p class="talk">'+response.msg+'</p></br>'; 
} 

更新

雖然這是一個有點晚了,你可以編碼數據成JSON。然後,當你使用它時,你可以解碼它。

<?php 
$response = json_decode(file_get_contents($filename)); 
$response->timestamp = $currentmodif; 
echo json_encode($response); 
flush(); 

當你寫郵件到該文件,您可以使用此:

<?php 
file_put_contents($filename,json_encode(array('msg'=>$msg,'name'=>$name))); 
+0

@LISON我試過這個 \t $ name \t = \t $ this-> session-> userdata('name'); $ msg = isset($ _ GET ['msg'])? $ _GET ['msg']:'';如果($ msg!='') { file_put_contents($ filename,$ msg,$ name); die(); } $ response ['msg'] = file_get_contents($ filename); $ response ['name'] \t = file_get_contents($ filename); bt我無法獲得價值... – 2013-03-01 14:08:59

+0

我其實是指我如何從文件file_get_contents($文件名)中獲取特定數據...... – 2013-03-01 14:26:40

+0

如果我不想使用文本文件並且想要使用我的文件自己的數據庫來存儲它...... 我已經做到了它和值存儲在數據庫bt它不顯示結果代碼它在這個網站[鏈接] http://jsfiddle.net/azamalvi/CGYWp/1 / – 2013-03-02 11:11:51

2

你應該使用這個希望將工作

 file_put_contents($filename, implode(';', array($msg, $name))); 
    $response = explode(';', file_get_contents($filename)); 
    $response[0] is your msg and $response[1] is your name. 

感謝nostrzak