javascript - js EventSource
本文介绍了javascript - js EventSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
客户端:
var source = new EventSource("http://controller.shujudaping.com:8084?token=1");
服务器端:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$token = $_GET['token'];
echo "token: The token is: {$token}\n\n";
flush();
?>
怎么才能在服务器端拿到token的数据?
解决方案
又自立自强了!!!
前台用event.data获取服务器端的数据
document.ready(function() {
document.domain = 'shujudaping.com';
var source = new EventSource("http://controller.shujudaping.com:8084/?token=2");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
})
服务器端:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$token = $_GET['token'];
echo "data: The token is: ---{$token}---\n\n";
flush();
?>
我之前在前台获取服务器的数据是通过event.data来获取,但是在服务器端处理请求的时候写的是echo "token: The token is: ---{$token}---nn";将其改成echo "data: The token is: ---{$token}---nn";就可以了.但是当我不改服务器端的echo "token: The token is: ---{$token}---nn";而是在前台将event.data改成event.token却不行.
这篇关于javascript - js EventSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文