duanbeng8872
2016-10-19 15:16 阅读 87

如何在数据库中的任何表中进行更新时从数据库获取数据

Like some user x updates some info on website and some other user z should receive a notification about x's update without he refreshing the page.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    dongliyun3301 dongliyun3301 2016-10-19 15:28

    This is a very large question that implies a lot of different notions. You should work at different levels (server, client and database) with multiple possibilities each time.

    1) client pull

    In the client page (user Z), you should send AJAX requests every once in a while (every 1 sec?) and the script on the server side should detect what values have been changed since the last request. This heavily relies on the existence of a timestamp field that is updated using triggers on every SQL insert or update (or delete?).

    2) server push

    Using websockets, the client (user Z) keeps an open connection to the server. On the server, a process is running constantly in the background and periodically checks the database (every 1 sec?) for updates (again based on timestamps) and sends the difference to the client on the websocket.

    Detect changes

    If your database does not fix some identifiable timestamp or id or else, you may try to execute an external program using triggers which will probably add another level of complexity.

    点赞 评论 复制链接分享
  • douyou3619 douyou3619 2016-10-19 15:26

    Without getting too technical, you could use a combination of an event dispatcher and a method to push notifications (like a websocket service).

    Your websocket service should subscribe to your event dispatcher.

    When an update takes place, dispatch an event, which your socket service will then use to send out the data to the proper set of users.

    On the web app's side, you'll of course have to be subscribed to the websocket and then do whatever's needed with the data that comes in.

    This method (using the event dispatcher) means your services are not tightly coupled and therefore more maintainable and testable.

    点赞 评论 复制链接分享
  • dqbjvg2518 dqbjvg2518 2016-10-19 15:36
    window.setInterval(function(){
      /// ajax call here, for example:
        $.ajax({
           type: "POST",
           url: 'your-url-to-check-if-there-is-any-updates',
                 dataType: "html",
                 data: { your data},
                 success: function(data) {
                  // do something with notifications
                  return data;
                 }
       });
    }, 5000);
    

    This will check your table every 5 seconds. You will need to send old data to url to check if there is something new, and if so, do something in success function.

    However, this is not recommended.

    As @Simon said, use websockets, for example: sockets.io

    点赞 评论 复制链接分享

相关推荐