jQuery jGrowl来自PHP文件的动态Ajax通知

艾哈迈德

我已经将jQuery jGrowl加载到主题中,并且能够显示如下通知:

jQuery.jGrowl('This is a notification', { life: 10000});

但是,我有一个每30秒重新加载一次的函数,并且已将jGrow通知放入其中,如下所示:

setInterval(function() {
    jQuery.jGrowl('This is a notification', { life: 10000});
}, 30000);

我希望基于php文件发回的信息动态地进行通知。php文件基本上返回了新消息的列表,我希望jGrowl为这些新消息中的每一个显示通知。不确定获取php文件以输出数据的最佳方法是什么,以便jGrowl可以理解它以及如何做到这一点。

任何建议将是巨大的。

谢谢

斯坦勒蒙

您需要使用类似jQuery的$ .ajax()方法的方法来轮询数据端点。我建议以JSON返回它,然后循环遍历并将其作为消息传递给$ .jGrowl方法。

您可以尝试以下示例:

index.html

<!doctype>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.3/jquery.jgrowl.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.3/jquery.jgrowl.min.js"></script>
<script>
$(function(){
    $('form').submit(function(e){
        e.preventDefault();

        $.ajax({
            type: 'get',
            url: $('form').attr('action'),
            data: $('form').serialize(),
            success: function() {
                $('input[type=text]').val('');
            }
        });
    });

    setInterval(function(){
        $.ajax({
            dataType: 'json',
            url: 'messages.php',
            success: function(messages) {
                $.each(messages, function(message){
                    $.jGrowl('This is a notification', { life: 10000});
                });
            }
        });
    }, 5000);
});
</script>
<body>
  <form method="get" action="addMessage.php">
    <input type="text" name="message" placeholder="New message" />
    <input type="submit"/>
  </form>
</body>
</html>

addMessage.php

<?php
session_start();
if (!isset($_SESSION['messages'])) {
    $_SESSION['messages'] = array();
}
if (isset($_GET['message']) && !empty($_GET['message'])) {
    $_SESSION['messages'][] = strip_tags($_GET['message']);
}
print json_encode($_SESSION['messages']);

messages.php

<?php
session_start();
if (!isset($_SESSION['messages'])) {
    $_SESSION['messages'] = array();
}
print json_encode($_SESSION['messages']);

我不建议在生产环境中使用此功能,您将希望更好地控制和清理消息,但这应该使您大致了解如何轮询消息并将其传递给jGrowl。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章