2016-09-19 30 views
-1

我做了一個簡單的聊天應用程序,一切工作正常, ,但請讓我知道如何停止附加相同的數據,如循環在setInterval的ajax調用中, 。這是我的代碼如何停止從ajax呼叫追加相同的數據爲mysql造成setInterval

setInterval(function() { 
    get_ajax_msg(); 
}, 5000); 

function get_ajax_msg(){ 
    //AJAX CALL// 
    $.ajax({ 
     url: "msg.php", 
     data:'act=check&id='+call_id+'&fid='+call_fid, 
     type: "POST", 
     success: function(data) { 
      if(data !=""){ 
       $('#ctlist').append(data); 
      } 
     } 
    }); 
    //END AJAX CALL// 
} 

PHP代碼

$msg_id= $_POST['id']; 
$runmsg = $db->query("SELECT * FROM chat_msg WHERE pid=". $msg_id ." ORDER BY date DESC LIMIT 1"); 

while ($mymsg = $db->fetch_array($runmsg)) { 
    echo $mymsg['msg']; 
} 
+0

你試過了什麼? –

+0

獲取聊天框的消息 –

+0

簡單:不要獲取所有消息。只有在您上次要求更新後纔會收到消息。這意味着你需要做'where date> $ last_request'類型的東西。 –

回答

0

簡單的方法不改變大部分代碼邏輯,存儲附加信息的ID,然後追加只有那些不在列表中的id 。它不是最不是最有效的方式,但它是對原始代碼的最小改變。 (請注意,我用下劃線進行迭代的數組,你可以用別的東西):

var oldIds = {}; 
setInterval(function() { 
    get_ajax_msg(); 
}, 5000); 

function get_ajax_msg(){ 
    //AJAX CALL// 
    $.ajax({ 
     url: "msg.php", 
     data:'act=check&id='+call_id+'&fid='+call_fid, 
     type: "POST", 
     success: function(data) { 
      if(data !=""){ 
       // iterate over each item in the returned array 
       _.each(data, function(item){ 
        // if item id is not present in the known list then 
        if(_.isUndefined(oldIds[item.pid])){ 
         // mark it as present 
         oldIds[item.pid] = true; 
         // append that item to the element 
         $('#ctlist').append(item); 
        } 
       }); 

      } 
     } 
    }); 
    //END AJAX CALL// 
} 

OFC,在理想的世界裏,你想改變你的請求到服務器的參數,送你只新消息,除非您的舊消息可能會更改或可能插入其中。

0

你需要很多的保障,如果你將遵循這樣:
1 - 首先,你需要跟蹤最後收到的消息ID從下一個 2-啓動後的最後一次,因爲代碼最終只有阿賈克斯再次打電話在使該消息順序的請求的延遲是不正確的 3-獲取所有新消息不一一

JS CODE:

var last_id = 0; 
function get_ajax_msg(){ 
    $.ajax({ 
     url: "msg.php", 
     data:'act=check&id='+call_id+'&fid='+call_fid+'&last_id='+last_id, 
     type: "POST", 
      success: function(data) { 
       if(data !=""){ 
        // parse the json data 
        data = JSON.parse(data); 
        last_id = data["last_id"]; 
        // Add the list of comments 
        for (var i = 0 ; i < data["msg"]; i++) 
         $('#ctlist').append(data["msg"][i]+"<br>"); 
       } 
       // Run again after finishing the first request 
       setTimeout(function() { 
        get_ajax_msg();  
       }, 5000); 
      } 
    }); 
} 
// Run it for the fisrt time 
get_ajax_msg(); 

PHP CODE:

$msg_id= $_POST['id']; 
$last_id = intval($_POST['last_id']); 
// Get all new comments 
$runmsg = $db->query("SELECT * FROM chat_msg WHERE pid=". $msg_id ." and `id` > '$last_id' ORDER BY date DESC"); 
$info = []; 
while ($mymsg = $db->fetch_array($runmsg)) 
{ 
    // append to the array of messages 
    $info[] = $mymsg['msg']; 
    // set the last used id 
    $last_id = $mymsg["id"]; 
} 

echo json_encode({"msg": $info, "last_id": $last_id});