【问题标题】:var notification = new Notificationvar 通知 = 新通知
【发布时间】:2015-04-21 09:38:11
【问题描述】:

所以我试图弄清楚这段 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>

【问题讨论】:

  • 完成此任务的最简单方法是执行 xmlhttprequest ... 每分钟左右说一次?检查是否有可用的更新。

标签: javascript html sql database


【解决方案1】:

要访问您的数据库,您需要 PHP。

如果你想在网页上执行PHP而不重新加载它,你必须像@Grimbode所说的那样使用“xmlhttprequest”。

这是一种通过 Javascript 从 PHP 函数获取 PHP 响应(在您的情况下是访问您的数据库)的方法。

为方便起见,您应该查看$.post method from jQuery

祝你研究顺利!

【讨论】:

    【解决方案2】:

    这是一个脚本,它会每分钟调用一次以检查是否有新通知。

    您的回复文本完全由您决定。你可以发回一个号码,你可以发回一个包含所有信息的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.ini 文件。每次调用 ajax 请求时,处理该请求的 php 文件都必须访问数据库并发回正确的响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多