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

本文介绍了如何通过Long Polling和WebSocket技术,利用Notify Server来实现网页即时获取通知消息的功能,提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一些场景中,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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值