服务器端事件& Ajax请求

时间:2017-08-14 11:57:58

标签: javascript php jquery ajax

使用PHP和JavaScript我试图在我的网站上添加一个按钮,以“恢复”实时数据源。我可以成功地“停止”饲料,我只是在努力再次开始它。

当我停止Feed时,我正在保存来自服务器的lastEventId。当我单击开始按钮时,我重新使用此值并向服务器发送AJAX请求。这有效,我可以检索lastEventId

我需要一些帮助从停止的位置再次启动Feed。

我的 JS 代码;

<script type="text/javascript">
       $("document").ready(function(){
           var lastSerial;
           var source = new EventSource("data.php");

           source.onmessage = function(event) {
               lastSerial = event.lastEventId;
               document.getElementById("result").innerHTML += "New transaction: " + event.data + "<br>";
               console.log(event.lastEventId); // returns the `lastEventId`
           };
           $("#start").click(function(){
               $.ajax({
                   type: "POST",
                   url: 'data.php',
                   data: {lastSerial: lastSerial},
                   success: function(data){
                       // need to start the feed again here from where it left off, based on the returned `lastSerial` value
                       console.log(lastSerial) // returns an INT as expected
                   }
               });
           });
           $("#stop").click(function(){
               source.close();
           });
       });//end dom ready
</script>

<div id="result"><!--live feed here--></div>
<button id="stop"> stop</button>
<button id="start"> start</button>

我的 data.php (简化);

if(isset($_POST['lastSerial'])) {
    // SELECT TimeStamp, SerialNo ... WHERE SerialNo >= 'lastSerial' ...
    // fetch results
    // echo "data: " .$row["SerialNo"]. "\n\n";
}

事实证明,我可以成功停止饲料。当我单击开始时,lastSerial将记录到控制台。

感谢任何建议。

1 个答案:

答案 0 :(得分:1)

而不是使用source.close()使用标记来确定Feed是否已停止。

var is_stopped = false;

[...]

$("#stop").click(function(){
    is_stopped = true;
});

然后,

source.onmessage = function(event) {
    /** If it is NOT stopped. **/
    if (!is_stopped) {
        lastSerial = event.lastEventId;
        document.getElementById("result").innerHTML += "New transaction: " + event.data + "<br>";
        console.log(event.lastEventId); // returns the `lastEventId`
    }
};

或者,

source.onmessage = function(event) {
    /** If it IS stopped. **/
    if (is_stopped)
        return false;

    lastSerial = event.lastEventId;
    document.getElementById("result").innerHTML += "New transaction: " + event.data + "<br>";
    console.log(event.lastEventId); // returns the `lastEventId`
};

这样您就不会实际查杀该事件,因此当您想要重新启动Feed时,只需将is_stopped设置为false,所有内容都会像之前一样恢复。

相关问题