2017-06-03 75 views
0

我建立了一個使用ajax和jQuery的聊天系統。每當收到消息時,我都希望有一個提醒。成功的ajax請求提醒

這裏的Ajax代碼接收新的消息

$(document).ready(function ajax(){ 
    $.ajax({ 
    type: 'GET', 
    url: 'recieve.php', 
    dataType: 'html', 
    success: function(response){ 
     $("#message").html(response); 
    }, 
    complete: function(){ 
     setTimeout(ajax,1000); 
    } 
    }); 
    }); 

我應該在哪裏放警報(「收到的新郵件」);所以它只有在收到消息時纔會彈出。

如果我把警報放在成功的功能,它是每秒彈出。

+0

由於正在執行的功能是每一秒的警報會彈出每一秒。您需要根據是否有新消息檢查響應和有條件提醒 – Colwin

+0

我知道並且只是想知道 – Arun

+0

如何嘗試使用某些能夠從服務器推送消息的框架,而無需客戶端每次請求。如'signalr' – Mark

回答

2

嘗試是這樣的:

var msg_res =''; //store the previous response 
$(document).ready(function ajax(){ 
    $.ajax({ 
    type: 'GET', 
    url: 'recieve.php', 
    dataType: 'html', 
    success: function(response){ 
     $("#message").html(response); 
     //if response changed, not the same as in msg_res 
     if(response != msg_res){ 
     msg_res = response; //store new response 
     alert('New message received'); 
     } 
    }, 
    complete: function(){ 
     setTimeout(ajax,1000); 
    } 
    }); 
}); 
+0

非常感謝:)這正是我一直在尋找 – Arun