繁体   English   中英

JQuery / Ajax每60秒检查一次用户消息

[英]JQuery / Ajax Check User Messages Every 60 Seconds

我运行的网站现在具有通知功能,我想运行一个脚本,每60秒左右检查一次新消息。 我需要做的是通过脚本传递使用ID,然后创建一个警报(到目前为止,我已经使用了基本的浏览器警报),但是我的代码似乎无法正常工作。 这是我到目前为止的代码:

JQuery

<script type="text/javascript">
$(document).ready(function()
{
var check;
var yourid = <?php echo json_encode($yourid); ?>;
function checkForMessages() {
    jQuery.ajax({
        type: 'POST',
        url: 'php/check-messages.php',
        data: 'id='+ yourid,
        cache: false,
        success: function(response){
            if(response = 1){
                clearInterval(check);
                alert("You have mail!");
            }
            else {}
        }
    });
}
check = setInterval(checkForMessages, 60000);
};
</script>

Check Messages PHP

<?php
include("settings.php");

$id= mysqli_real_escape_string($con, $_REQUEST["id"]);

$check_messages_sql = "SELECT * FROM notes WHERE recipient = '$yourid' AND seen = '0'";
$check_messages_res = mysqli_query($con, $check_messages_sql);
if(mysqli_affected_rows($con)>0){
echo "1";
}
?>

怎么样?

function checkForMessages(yourid) {
    jQuery.ajax({
        type: 'POST',
        url: 'php/check-messages.php',
        data: 'id='+ yourid,
        cache: false,
        success: function(response){
            if(response = 1){
                clearInterval(check);
                alert("You have mail!");
            }
            else {}
        }
    });
}
check = setInterval(checkForMessages(yourid), 60000);

您可以使函数递归,并添加60秒的延迟:

function checkForMessages() {

    var dataObj = {};
    dataObj['id']= yourid;

    jQuery.ajax({
        type: 'POST',
        url: 'php/check-messages.php',
        data: dataObj,
        cache: false,
        success: function(response){
            if(response == 1){
                clearInterval(check);
                alert("You have mail!");
            }
            else {}
        }
    });
    setTimeout(
      function() 
      {
        checkForMessages();
      }, 1000);

}

这样,您的功能将每1000毫秒重新启动一次。

尝试使用if(response == 1)检查,并设置超时如下。

setTimeout(function() {checkForMessages();}, 2000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM