jquery:使用PHP和AJAX不刷新页面的新事件通知

文章讲述了如何在不刷新页面的情况下显示新增事件的通知。作者目前的实现方式是基于PHP和jQuery,当页面加载时查询事件总数并显示。为了实现动态更新,作者考虑使用AJAX长轮询(longpolling)技术,通过定时发送请求到服务器检查新事件,当有新事件时立即反馈给前端更新计数。文中还提及了ThinkPHP框架以及对使用Swoole或Workerman等技术的提及作为替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每次将新事件添加到我的数据库时,我都会向我的用户显示通知。我的首页上有一个小图标,还有一个红色方块来显示添加的新事件的数量。现在我只想知道在不刷新页面的情况下显示新事件的最佳方法是什么。

这是我的代码

1
2
3
4
5
6
7

<li>
<i class="fa fa-warning  fa-2x">
    <?php if ($totalRows_event > 0) { ?>
        <span class="label label-danger blink"><?php echo $totalRows_event ?></span>
    <?php } ?>

</li>

我的PHP查询基本上是事件总数>0的时候,显示一个<span>和里面的总数,但是这只在页面刷新或者加载的时候显示。

我正在查看一个类似于下面的 AJAX 请求,它将 PHP 查询结果显示到内部 html 中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14

function testAjax() {
    var result ="";
    $.ajax({
        url:"data.php",
        async: false,
        success: function (data, textStatus) {
            $("#preview").html(data);
        },
        error: function () {
            alert('Not OKay');
        }
    });
    return result;
}

1
2
3
4
5
6

<li>

  <i class="fa fa-warning fa-2x">
  <span class="label label-danger blink" id="preview"></span>

</li>

但是,每次将新事件添加到我的数据库时,我如何调用该函数而不刷新或加载页面?我认为使用设置的时间间隔或延迟会因为频繁的服务器查询而减慢我的页面,所以我正在寻找其他选项。


php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

 public function index()
    {
        if (!$_GET['timed']) exit();
        if (!$_GET['uid']) exit();
        date_default_timezone_set("PRC");
        set_time_limit(0);
        $uid = $_GET['uid'];
        while (true) {
            sleep(3);
            $lastReadTime = M('readtime')->where(array('uid'=>$uid))->field('lasttime')->select();
            $result = M('message')->where(array('send_time'=>array('gt',$lastReadTime),'touid'=>$uid))->count();
            if($result){
                $data = array(
                    'message' => $result,
                );
                echo  json_encode($data);
                exit();
            } else {
                usleep(1000);
                exit();
                //return;
            }
        }
        session_write_close();
    }

js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

 var cometURL ="{:U(GROUP_NAME.'/Comet/index')}"
    $(function () {
        (function longPolling() {
            //alert(Date.parse(new Date())/1000);
            $.ajax({
                url: cometURL,
                data: {"timed": Date.parse(new Date())/1000,"uid":$("#uid-hidden").val()},
                dataType:"json",
                timeout: 5000,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (textStatus =="timeout") {
                        longPolling();
                    } else {
                        longPolling();
                    }
                },
                success: function (data, textStatus) {
                    if(data.message != 0){
                    $(document.body).append("<i class='iconfont'style='position: fixed;top: 28px;right: 30px;color: #2fa8ec;font-size: 20px'>");
                    $("#messagenum").html('message('+data.message+')');
                    }
                    if(data.image != 0){
                        $(document.body).append("<i class='iconfont'style='position: fixed;top: 28px;right: 30px;color: #2fa8ec;font-size: 20px'>");
                        $("#imagenum").html('New Image('+data.image+')');
                    }
                    if (textStatus =="success") {
                        longPolling();
                    }
                }
            });
        })();
    });

我正在使用 THINKPHP 和 Jquery,你可以将其更改为你的方式。(AJAX LONG PULLING)。或者如果你的工作区在 linux 中,你可以使用 swoole 或 workerman 或 websocket 来制作。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值