我已经将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。