简体   繁体   English

setInterval是获取通知的正确方法吗?

[英]setInterval is it the correct way to get notifications?

i need to create a messages notifications in my system built by yii2 , 我需要在yii2构建的系统中创建消息通知,

so i used this way 所以我用这种方式

1- i created in messages Controller function getnew : 1-我在消息控制器功能getnew中创建了:

public function actionGetnew()  
{
     $query1 = new Query;                              
      $query1->select([" count(*) as  price "]   )
              ->from('messeges');
              //->where // here   i will add the id of user that logged in and the state of unread messages ! 
     $command1 = $query1->createCommand();
     $price = $command1->queryAll();  
     echo Json::encode($price); 
}

2- i created a js file : 2-我创建了一个js文件:

window.onload = function() {

   setInterval(function(){ 
    $.get('index.php?r=messeges/getnew',function(data)
    {
        var data=$.parseJSON(data);

        $(".messages").html(data[0].price);
    });
 }, 5000);
};

3- i added HTML tag like this : 3-我添加了这样的HTML标签:

  <h6 class="messages"></h6>

everything work fine but my question is that right way to do it ? 一切正常,但是我的问题是正确的方法吗? , is that will add more traffic and load on my server ? ,这是否会增加服务器的流量和负载? if there is a better idea please notify me ! 如果有更好的主意,请通知我!

It isn't best way to do this. 这不是最好的方法。

You are right - it could cause traffic and load increase. 没错-这可能会导致流量和负载增加。

Better options are: 更好的选择是:

  1. Longpooling Longpooling

  2. Server events 服务器事件

  3. WebSockets 的WebSockets

First of all try to consider socket.io (they have some problems with website - try to go on it later :-) ) 首先尝试考虑socket.io (它们在网站方面存在一些问题-稍后再尝试进行:-))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM