所以我试图弄清楚这段JavaScript。我正在尝试做的事情是使用查询来显示数据库中的通知数量。因此,假设我的数据库中有 5 条通知,是否可以向此代码添加查询,以便它显示以下内容:您好,您有 5 条看不见的消息?我现在有垃圾箱搜索几个小时,它只是让我发疯。
提前致谢
<html>
<head>
<script language="javascript">
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check if the user is okay to get some notification
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user is okay, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
}
// At last, if the user already denied any notification, and you
// want to be respectful there is no need to bother them any more.
}
</script>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><button onclick="notifyMe()">Meldingen ophalen</button></div>
</body>
</html>
要访问数据库,您需要 PHP。
如果你想在网页上执行PHP而不重新加载它,你必须使用"xmlhttprequest",如@Grimbode所说。
这是一种通过 Javascript 从 PHP 函数获取 PHP 响应(在您的情况下,可以访问您的数据库)的方法。
为了使事情变得更容易,您应该查看jQuery中的$.post方法。
祝你的研究好运!
这是一个脚本,它将每分钟调用一次自身以检查是否有新的通知。
您的回复文本完全取决于您。您可以发回一个号码,您可以发回包含所有信息的 json,等等。
setInterval(function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
new Notification("You have " + xmlhttp.responseText + " notifications!");
}
}
xmlhttp.open("GET", "php_ajax_handler_url_here", true);
xmlhttp.send();
}, 60000);
这需要你拥有 php。每次调用 ajax 请求时,处理该请求的 php 文件都必须访问数据库并发回正确的响应。