2017-06-03 54 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