我在这里有一块代码块,它使用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?
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>";
};
@blazonix在使用SSE时必须区分发送和接收。
EventSource仅用于从服务器接收数据。要将数据发送到服务器,您必须使用常规的AJAX请求。
在我的库中,我可以重复使用相同的路径进行发送和接收,但我根据Accept标头区分调用者想要做的事情:
示例java代码:GitHub
这很简单。
$.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.
});