入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

利用Notify Server实现WEB页面实时获取通知消息

创建时间:2016-12-26 投稿人: 浏览次数:2792
在一些场景中,WEB页面需要实时获取消息通知,例如网页展示一个二维码等待用户用手机扫描后执行某个操作(如登陆、绑定、支付等)。实现方法不外乎以下这几种,网上有很多说明:


1、HTTP刷新。可以放到隐藏的IFRAME当中,但是滚动条会经常闪动。无法真正实时,如果设置刷新频率过高,则对服务器和网路的压力很大,过低时等待端反应迟缓。


2、AJAX定时获取。实质跟上面一样。


3、HTML5 WebSocket。兼容性受限。在服务器端需要特别设计。


4、利用Flash,Java Applet,ActiveX等外来插件实现。兼容性差,需要在客户端配置。


5、长轮询(long polling)。应用最广,对客户端无要求。实际上是建立一个HTTP连接专门用于获取通知信息。可以用动态JS或者Ajax实现。Notify Server就是一个免费的实时通知服务,可以用跨域Ajax调用,推荐使用动态JS访问更自然,以下是示例代码:


Test1.html

<html><head><meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=gb2312">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
var $=function(s){return document.getElementById(s)};
$.require=function(s){
		var e=document.createElement("script");e.src=s;
		document.getElementsByTagName("head")[0].appendChild(e);
}
</script>
</head>
<body>
<input type=button value=开始等待通知 onclick=startWait()>
<script>
function cbNotify(){ //在得到通知后,服务器会回调cbNotify();
	alert("收到通知");
}
function startWait(){
	$.require("http://notify.wowotou.tech/wait?key=order1234xxxx"); //你的key最好要特别一点,避免跟其他人的key冲突
}
</script>
</body>
</html>


Test2.html

<html><head><meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=gb2312">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
var $=function(s){return document.getElementById(s)};
$.require=function(s){
		var e=document.createElement("script");e.src=s;
		document.getElementsByTagName("head")[0].appendChild(e);
}
</script>
</head>
<body>
<input type=button value=发送通知 onclick=notify()>
<script>
function notifySuccess(){ //服务器会根据发送结果回调notifySuccess()或者notifyFailed()
	alert("通知发送到对方");
}
function notifyFailed(){
	alert("没有人被通知,是否key错误?");
}
function notify(){
	$.require("http://notify.wowotou.tech/notify?key=order1234xxxx"); //key必须与等待方一致
}
</script>
</body>
</html>



声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像