通过服务器发送事件向PHP发送POST吗?

问题描述 投票:5回答:3

是否有可能像在Ajax中一样使用SSE将POST数据发送到PHP?

我已经使用AJAX相当长时间了,但在长轮询技术上却有不好的结果。我也一直在考虑WebSocket,但似乎有点多余。

php ajax post polling server-sent-events
3个回答
4
投票

否,SSE无法将任何数据发送到服务器。

您仍然可以使用SSE实时读取数据,并使用AJAX上传任何数据(您可能需要共享的数据库才能在AJAX接收过程和SSE发送过程之间传递信息。


0
投票

您可以通过GET发送数据。

例如

name=john&name=lea

这是一个简单的脚本,它使用SSE发送给服务器迭代次数,服务器返回进度。

此项目包含两个文件(index.php和ssedemo.php)。

index.php包含一个文本框和一个按钮。文本框应该包含ssedemo.php中循环的迭代数]

    <h2>Server Sent Event Test</h2>
    <form>
        <label>Process Duration</label>
        <input type="text" id="progVal">
        <input type="button" value="Get Messages" onclick="updateProgress()"/>
    </form>
    <div id="container">
    </div>

updateProgress

    function updateProgress() {
        var input = $('#progVal').val();
        var evtSource = new EventSource("ssedemo.php?duration=" + encodeURIComponent(input));
        evtSource.addEventListener("progress", function (e) {
            var obj = JSON.parse(e.data);
            $('#container').html(obj.progress);
            if(  parseInt(obj.progress) == 100){
                evtSource.close();
            }
        }, false);
    }

此函数使用jQuery获取文本框的内容,然后创建一个eventSource。 EventSource()构造函数带有一个或两个参数。第一个指定要连接的URL。第二个以EventSourceInit字典的形式指定设置(如果有)。

您可以像使用GET一样通过将其添加到URL来传递所需的信息。

"ssedemo.php?duration=" + encodeURIComponent(input)

在服务器端,您必须根据W3C recommendation设置头类型并禁用缓存

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

然后您照常使用$ _GET获取数据。

$TotalNo = $_GET['duration'];
for ($i = 1; $i <= $TotalNo; $i++) {
    updateProgress($i, $TotalNo);
    sleep(1);
}


function updateProgress($currentVal, $totalNo) {
    $completionPrecentage = $currentVal / $totalNo * 100;
    echo "event: progress\n";
    echo 'data: {"progress": "' . $completionPrecentage . '"}';
    echo "\n\n";
    ob_flush();
    flush();
}

如果要发送数组,可以参考this


0
投票

EventSource API不支持POST方法,但这并不意味着您不能将SSE与POST一起使用。您只是不能使用EventSource API。但是,还有其他实现方式。一个示例是sse.js,它允许您指定有效负载,并在需要时指定标头。 sse.js应该替代EventSource,例如:

var source = new SSE("get_message.php");
source.onmessage=function(event)
{
    document.getElementById("message-window").innerHTML+=event.data + "<br>";
};

为了使用POST方法,您只需要指定一个有效负载,例如:

var source = new SSE("get_message.php", {payload: 'Hello World'});

而且,由于它是完全兼容的polyfill,您可以执行以下操作:

EventSource = SSE;
var source = new EventSource("get_message.php", {payload: 'Hello World'});
source.onmessage=function(event)
{
    document.getElementById("message-window").innerHTML+=event.data + "<br>";
};
© www.soinside.com 2019 - 2024. All rights reserved.