Javascript 使用AJAX的Chrome通知
在页面加载时,我请求用户允许这样的通知:Javascript 使用AJAX的Chrome通知,javascript,php,jquery,google-chrome,Javascript,Php,Jquery,Google Chrome,在页面加载时,我请求用户允许这样的通知: document.addEventListener('DOMContentLoaded', function () { if (Notification.permission !== "granted") Notification.requestPermission(); }); 然后,我编写了一个向用户发送通知的函数,该函数运行良好: function push(title, message, location) {
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');
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);
然后我有了一个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()的范围,我发现了问题。我无法检索任何内容,因此我返回了如下响应值:
push('Test', 'Test Message', 'http://example.com');
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);
由于$.post()的作用域,我发现了问题。我无法检索任何内容,因此我返回了响应值,如下所示:
push('Test', 'Test Message', 'http://example.com');
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);