jQuery+ThinkPHP+Ajax Instant Message Reminder Instance Code

  • 2021-08-05 08:42:33
  • OfStack

On a whim, I want to make a reminder system for my small project, such as private letters, comments and other messages can be transmitted in time. Because the road is still shallow, the long polling on the Internet is slightly complicated for me, so I think it is better to write 1 by myself.

My idea is to build a reminder table in the database separately, which is mainly composed of two fields: id of the recipient and message type


/*  Front Desk Reminder Table  */
CREATE TABLE IF NOT EXISTS notification(
  id      INT NOT NULL AUTO_INCREMENT PRIMARY KEY,  --   Primary key self-increment 
  mid     INT NOT NULL DEFAULT 0,            --   Users id
  type    INT NOT NULL DEFAULT 0            -- 0 Private letter  1 : Post comments  2 Goods sold  3 Commodity Review  4 : Panel request sent  5 Team Creation Successfully  6 : New members of the group join  7 : Old team members quit  8 : Invitation to the event 
)ENGINE=MyISAM DEFAULT CHARSET=UTF8;

Then write a recursive function in the foreground page to request Ajax.


function require() {
   var url = "{U('Group/checkNotify')}";
        
   $.get(url,null,function(data) {
                    
      //  If the obtained data is not empty, a reminder is displayed 
      if ($.trim(data) != '') {
        //  The way to write reminders here 
              alert('haha');
      }
   });
   //  Every 3 Second request 1 Times 
   setTimeout('require()',3000);
}

Inquire whether there is data insertion in the database from 3 seconds ago to the current time in the background, and if so, return the required information


public function checkNotify() {
  //  Instantiate a custom model class 
  $Notify = D("Notification");
  //  Object for the current user id
  $mid = $_SESSION['member']['id'];
  //  Due to Ajax3 Seconds to execute 1 Therefore, the insertion time of new data will be later than the request time of the query (current time) 3 Seconds 
  $time = time() - 3;
  //  Prepare query criteria 
  $where = "mid = $mid and created>$time";
   //  Find out if there is new data insertion in the database 
  $bool = $Notify->where($where)->find();
  //  If the query result is not empty, the zero data of the result set is output type Parameter, that is, the reminder type, and then get the reminder content from the database corresponding table 
  // This test defaults 3 Only in seconds 1 If you want to be more accurate, you can also shorten the request time 
  if ($bool != null) {
    // Test data      
    echo $bool[0]['type'];
  };
}

Of course, let the function be executed after the document is loaded


<body onload="javascript:return require();">

Related articles: