2017-08-14 193 views
0

使用PHP和JavaScript我試圖向我的網站添加一個按鈕,它將「恢復」數據的實時提要。我可以成功'停止'飼料,我只是努力再次開始。服務器端事件和Ajax請求

當我停止供稿時,我保存來自服務器的lastEventId。當我點擊開始按鈕時,我重新使用這個值並向服務器發送一個AJAX請求。這工作,我能夠檢索lastEventId

我需要一些幫助從停止的地方再次啓動Feed。

我的JS code;

<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

而不是在做source.close()使用一個標誌來確定飼料是否已停止。

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` 
}; 

這樣,你實際上並沒有殺害事件,所以當你要重新啓動剛纔設置is_stoppedfalse飼料一切都像以前一樣恢復。

+0

@TheOrdinaryGeek在這種情況下,你可以用'is_stopped'來實際輸出數據。所以你會擁有它,但沒有實際顯示它。如果這個答案對你有幫助,考慮接受它。 – Script47

+0

@TheOrdinaryGeek是的,您可以使用localStorage並將其作爲JSON對象存儲,如果需要的話可以在恢復時進行檢索和比較。 – Script47

+0

Thanks @ Script47這是我目前正在努力工作的部分。我相信我最終會到達那裏:/ – TheOrdinaryGeek