【问题标题】:jQuery jGrowl dynamic ajax notification from php file来自 php 文件的 jQuery jGrowl 动态 ajax 通知
【发布时间】:2015-12-17 10:27:09
【问题描述】:

我已将 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 可以理解它以及如何做到这一点的最佳方法。

任何建议都会很棒。

谢谢

【问题讨论】:

    标签: php jquery ajax jgrowl


    【解决方案1】:

    您需要使用类似 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 2014-05-10
      • 1970-01-01
      • 2012-05-27
      • 2014-10-05
      • 1970-01-01
      相关资源
      最近更新 更多