duanbeng8872
2016-10-19 15:16
浏览 97

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

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.

图片转代码服务由CSDN问答提供 功能建议

像某些用户x更新网站上的某些信息,其他一些用户z应该收到有关x更新的通知,而无需刷新 页面。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • 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 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 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

    打赏 评论

相关推荐 更多相似问题