1
在頁面加載我請求用戶允許像這樣的通知:瀏覽器通知使用AJAX
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()
方法。
任何幫助將不勝感激。