在index.php上,我正在运行以下AJAX来获取更新的通知:
function updateNotifications() {
var user_id = "<?php echo $user_id; ?>";
var phpSessionId = "<?php echo session_id(); ?>";
var number_of_previous_notifications = "<?php echo $_SESSION['number_of_notifications']; ?>";
alert(number_of_previous_notifications);
$.ajax({
url : "notification_refresh.php",
type : "POST",
data : { "user_id": user_id, "session_id": phpSessionId },
success :
function(data) {
var response = $.parseJSON(data);
if (response.messages > 0) {
$('.inactive-notification-img').hide();
$('.notification-img').show()
$('.notification-number').html(response.messages).addClass('blink_me');
}
else {
$('.notification-img').hide();
$('.inactive-notification-img').show();
$('.notification-number').html('').removeClass('blink_me');
}
}
});
setTimeout('updateNotifications()', 15000); // Every 15 seconds.
}
updateNotifications();
在AJAX调用的页面上,这是代码...
if (isset($_POST['session_id'])) { session_id($_POST['session_id']); }
session_start();
include_once('../../inc/database.php');
include_once('../../inc/session.php');
if (
(isset($_POST['user_id'])) && (is_numeric($_POST['user_id']))
){
$notif_user_id = $_POST['user_id'];
$search_notif_query = $db1q->query("SELECT id FROM User_Notifications WHERE FIND_IN_SET('$notif_user_id', to_user) AND status = '0'");
$response = ['messages' => $search_notif_query->num_rows];
$_SESSION['number_of_notifications'] = $search_notif_query->num_rows;
echo json_encode( $response );
}
正如您所知道的,在index.php上的函数中,我正在警告number_of_previous_notifications以查看其是否发生了变化。我让函数运行4-5次,并且从未更新number_of_previous_notifications。
这是在告诉我,会话['number_of_notifications']尚未在Ajax请求页面上更新。
有什么想法吗?
答案 0 :(得分:1)
好的...如果存储变量old_notification_value
高于其先前值,建议您尝试播放声音:
var old_notification_value = 0; // A variable to store the notification amount over time
function updateNotifications() {
var user_id = "<?php echo $user_id; ?>";
var phpSessionId = "<?php echo session_id(); ?>";
var number_of_previous_notifications = "<?php echo $_SESSION['number_of_notifications']; ?>";
alert(number_of_previous_notifications);
$.ajax({
url : "notification_refresh.php",
type : "POST",
data : { "user_id": user_id, "session_id": phpSessionId },
success :
function(data) {
var response = $.parseJSON(data);
if (response.messages > 0) {
$('.inactive-notification-img').hide();
$('.notification-img').show()
$('.notification-number').html(response.messages).addClass('blink_me');
}
else {
$('.notification-img').hide();
$('.inactive-notification-img').show();
$('.notification-number').html('').removeClass('blink_me');
}
if(response.messages > old_notification_value){ // Here you handle the sound notification.
// Update the old_notification_value variable!
old_notification_value = response.messages;
// Then play a sound here!
}
}
});
setTimeout('updateNotifications()', 15000); // Every 15 seconds.
}
您试图通过$_session
变量来处理它...但是,事实是,一旦HTML生成并发送到客户端,服务器端和客户端之间就没有通信。对$_session
变量的更改不会不会反映在已经交付给客户端的网页中。
简而言之,您只能使用您拥有的json响应在客户端进行处理。忘记执行该任务的$_SESSION
。 ;)