首页 > 解决方案 > 如何在 PHP 和 python 中使用 HTML5 SSE

问题描述

我想简单地检查一下我的 API 端点是否还活着,但我得到了Firefox can’t establish a connection to the server at myURL错误,我在 94.0.1(64 位)Windows 版本上,这是基于的支持。我正在 AWS-ec2 上尝试这个。这一切都基于这篇文章:https ://www.w3schools.com/html/html5_serversentevents.asp

这是我的HTML

 <div id="searchDatabases"> 
 </div>
            <script type="text/javascript">
              if(typeof(EventSource) !== "undefined") {
                // Yes! Server-sent events support!
                var source = new EventSource("pingServers.php");
                source.onmessage = function(event) {
                    document.getElementById("searchDatabases").innerHTML = event.data + "<br>";
                };

              } else {
                // Sorry! No server-sent events support..
                console.info("Not supported browser!");
              } 
            </script>

这是在pingServers.php

    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');


    $output = shell_exec("python3 pingServers.py")

    echo $output;

    flush();

这是pingServers.py

#!/usr/bin/python
import requests
import json 
import html
import sys

requestpost = requests.post('MyJSONEndpoint.php')
if requestpost.status_code == 200:
    print('OK')
else:
    print('not OK')

所以我的问题是我怎样才能正确地做到这一点?

标签: javascriptpythonphphtmlserver-sent-events

解决方案


推荐阅读