如何通过HTML SSE传递POST参数? [英] How to pass POST parameters with HTML SSE?

查看:598
本文介绍了如何通过HTML SSE传递POST参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

以下是代码:

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吗?

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

推荐答案

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

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

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

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'});

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

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

这篇关于如何通过HTML SSE传递POST参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆