我正在尝试使用 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";
}
就目前情况而言,我可以成功停止 feed。当我单击开始时,lastSerial
会记录到控制台。
如有任何建议,我们将不胜感激。
最佳答案
不要执行 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
,一切都会像以前一样恢复。
关于javascript - 服务器端事件和 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674036/