如何使用HTML SSE传递POST参数?

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

我在这里有一块代码块,它使用HTML 5 SSE - EventSource对象,它允许php脚本将更新推送到网页。但是,我也对将参数传递给脚本感兴趣。我怎样才能做到这一点?

这是代码:

if(typeof(EventSource) !== "undefined")
    {
        var source = new EventSource("get_message.php");
        source.onmessage=function(event)
        {
            document.getElementById("message-window").innerHTML+=event.data + "<br>";
        };
    }
else
    {   
        document.getElementById("message-window").innerHTML="Sorry, your browser does not support server-sent events...";
     }

我能想到的最接近的是使用AJAX,就像在

$.post("get_message.php", {largest_id: 30}, function(data, status){ some function });

但是,我不知道如何为此编写jQuery?

javascript php jquery html server-sent-events
3个回答
2
投票

EventSource API不支持POST方法,但这并不意味着您不能将POST与SSE一起使用。你不能使用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>";
};

-1
投票

@blazonix在使用SSE时必须区分发送和接收。

EventSource仅用于从服务器接收数据。要将数据发送到服务器,您必须使用常规的AJAX请求。

在我的库中,我可以重复使用相同的路径进行发送和接收,但我根据Accept标头区分调用者想要做的事情:

  • 接受:text / event-stream - 它是一个浏览器,想要启动事件流连接
  • 接受:任何其他类型 - 它是常规的非/ AJAX调用GET或POST

示例java代码:GitHub


-1
投票

这很简单。

$.post('your_url.php?your_parametre1=' + your_value1 + '&your_parametre2_likewise=' + your_value, function(data) {
alert(data); // whatever you echo from php file as a identifier of success or error.
});
© www.soinside.com 2019 - 2024. All rights reserved.