WebSockets API
EventSource() 构造函数返回一个新建的EventSource,它代表了一个远程资源。
语法
pc = new EventSource(url, configuration);
参数
url- : 一个String ,它代表远程资源的位置
configuration- : 为配置新连接提供选项。可选项是:
withCredentials,默认为false,指示 CORS 是否应包含凭据 ( credentials )。
- : 为配置新连接提供选项。可选项是:
返回值
一个新建的 EventSource 对象,如果指定了configuration,则按其配置;否则,配置为合适的基本默认值。
示例
var evtSource = new EventSource("sse.php");
var eventList = document.querySelector("ul");
evtSource.onmessage = function (e) {
var newElement = document.createElement("li");
newElement.textContent = "message: " + e.data;
eventList.appendChild(newElement);
};
[!NOTE] 你可以在 GitHub 查看完整示例 — 请查看 Simple SSE demo using PHP.
规范
浏览器兼容性
参见
- EventSource
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
