How to pass POST parameters with HTML SSE?

这一生的挚爱 提交于 2019-12-10 17:12:02

问题


I've got a block of code here that uses HTML 5 SSE - the EventSource object, which lets a php script push updates to the webpage. However, I'm interested in also passing parameters to the script. How can I do that?

Here's the code:

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...";
     }

The closest thing I can think of is to use AJAX, as in

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

However, I'm not sure how to write the jQuery for this?


回答1:


The EventSource API does not support POST method, however that does not mean that you cannot use SSE with POST. You just cannot use the EventSource API.
There are alternative implementations however. One example is sse.js which allows you to specify a payload, and also headers if you need. sse.js should be a drop-in replacement for EventSource, eg:

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

In order to use a POST method, you just need to specify a payload, eg:

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

And, since it is a fully compatible polyfill, you can probably do this:

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



回答2:


@blazonix you must differentiate between sending and receiving when using SSE.

EventSource is meant only for receiving data from server. To send data to server you must use regular AJAX request.

In my library I'm making it possible to reuse the same path for sending and receiving but I'm distinguishing what the caller wants to do based on Accept header:

  • Accept: text/event-stream - it is a browser and wants to initiate event stream connection
  • Accept: any other type - it is a regular non/AJAX call GET or POST

Sample java code: GitHub




回答3:


That is so simple.

$.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.
});


来源:https://stackoverflow.com/questions/23825771/how-to-pass-post-parameters-with-html-sse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!