在页面加载时,我请求用户允许这样的通知:
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
我写了一个函数来发送通知给用户,它工作得很好:
function push(title, message, location) {
if(!Notification) { return; }
if (Notification.permission !== "granted") { return; }
var notification = new Notification(title, {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: message,
});
notification.onclick = function () {
window.open(location);
};
}
像这样使用:
push('Test', 'Test Message', 'http://example.com');
然后我有一个PHP脚本,目前它是静态的,并返回相同的东西测试很快是数据库驱动。
session_start();
header('Content-Type: application/javascript');
if(!isset($_SESSION['notify'])) {
echo json_encode(array(
'Title' => 'Welcome to our Site',
'Message' => 'You are current recieving notifications.',
'Location' => 'http://example.com/',
'State' => true
),true);
$_SESSION['notify'] = true;
} else {
echo json_encode(array(
'State' => false
), true);
}
当页面被直接访问时,这也可以正常工作。这个问题发生在我的AJAX请求中:
setInterval(function() {
$(document).ready(function() {
$.post('../notify/get_notify.php').done(function(response) {
if(response.State) {
push(response.Title, response.Message, response.Location);
}
console.log(response);
});
});
}, 5000);
问题就在这里!当我检查网络时,每隔5秒就会发出一个请求并返回响应。但是,控制台没有记录任何内容,并且没有执行push()
方法。
我发现了这个问题,由于$.post()
的范围,我无法检索任何东西,所以我返回了响应的值,如下所示:
setInterval(function() {
$(document).ready(function() {
response = $.post('../notify/get_notify.php').done(function(response) {
return response;
});
if(response.State) {
push(response.Title, response.Message, response.Location);
}
});
}, 5000);