如何使用PHP和Jquery开发像facebook这样的警报系统?

Ale*_*hew 10 css php jquery notifications

我如何开发像Facebook这样的警报系统,其中用户A添加用户B,用户B将在标题上的朋友请求部分获得一些号码,如下图所示.我该如何开发类似的东西?我们怎样才能获得这样的数字?我如何在PHP和JQuery中获取代码?
替代文字

mko*_*nen 17

我认为你想要一种警告用户A的方法,当用户B'朋友'他/她而不需要刷新页面时?

这需要"AJAX".AJAX代表异步Javascript和XML,但现在这是一个重载的术语,实际的交换数据结构通常使用JSON而不是XML.JSON是JavaScript Object Notation.无论如何,我们的想法是,您的网页 - 无需刷新 - 可以定期调用您的服务器以获取新的或更新的信息以更新显示.使用PHP和jQuery,您需要首先在页面上设置AJAX调用,如下所示:

$(function() { // on document ready

function updateAlerts() {
   $.ajax({
      url : "/check.php",
      type : "POST",
      data : {
         method : 'checkAlerts'
      },
      success : function(data, textStatus, XMLHttpRequest) {
         var response = $.parseJSON(data);

         // Update the DOM to show the new alerts!
         if (response.friendRequests > 0) {
            // update the number in the DOM and make sure it is visible...
            $('#unreadFriendRequestsNum').show().text(response.friendRequests);
         }
         else {
            // Hide the number, since there are no pending friend requests
            $('#unreadFriendRequestsNum').hide();
         }

         // Do something similar for unreadMessages, if required...
      }
   });
   setTimeout('updateAlerts()', 15000); // Every 15 seconds.
}

});
Run Code Online (Sandbox Code Playgroud)

这将每隔15秒向您的服务器发送一个请求,该请求位于与网页原点相同的域中的url /check.php上.PHP应查询您的数据库并返回未读的好友请求数.也许是这样的:

<?php

   function isValid(session) {
      // given the user's session object, ensure it is valid 
      // and that there's no funny business
      // TO BE IMPLEMENTED
   }

   function sanitize(input) {
      // return CLEAN input
      // TO BE IMPLEMENTED
   }

   // Be sure to check that your user's session is valid before proceeding, 
   // we don't want people checking other people's friend requests!
   if (!isValid(session)) { exit; }

   $method = sanitize($_POST['method']);

   switch ($method) {
      case 'checkAlerts' :
         // Check DB for number of unread friend requests and or unread messages
         // TO BE IMPLEMENTED

         $response = ['friendRequests' => $num_friend_requests,
                      'messages' => $num_unread_messages ];

         return json_encode( $response );
         exit;

      case 'someOtherMethodIfRequired' :
         // ...
         exit;
   }
?>
Run Code Online (Sandbox Code Playgroud)

  • 实际上,FB和其他人可能实际上在较新的浏览器中使用WebSockets,这允许他们推送更新而不是使用轮询(就像AJAX那样).它还节省了必须构建和销毁大量Web服务器进程的开销(在大多数情况下,每个AJAX请求一个). (3认同)