* 本文章仅包含数据推送,前端部分内容 *
Comet
基于HTTP长连接的服务器推送技术
就是前端向后台发送一个请求,后台进行一个死循环,一直向前端发送信息.
- 使用jQuery
function conn(){
$.ajax({
url:'/action'
type:'get',
dataType:'json',
success:function(data){
console.log(data)
conn()
}
})
}
conn()
- 使用axios
function conn(){
axios.get('/action').then(response=>{
console.log(response.data)
conn()
}).catch(err){
console.log(err)
}
}
conn()
- 使用原生js
function createXHR(){
var xhr = null
if(typeof XMLHttpRequest !== undefined){
xhr = new XMLHttpRequest()
createXHR = function(){
return new XHLHttpRequest()
}
}else{
try{
xhr = new ActiveXObject('Microsoft.XMLHTTP')
createXHR = function(){
return new ActionXObject('Microsoft.XMLHTTP')
}
}catch(e){
xhr = null
createXHR = function(){
return null
}
}
}
return xhr
}
var xhr = createXHR()
xhr.open('GET','/action',true)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState === 3 && xhr.status === 200){
console.log(xhr.responsetText)
}
}
基于WebSocket的推送方案
和后台建立稳定的websocket连接.然后接收,发送数据
var ws = null
function init(){
ws = new WebSocket('ws://localhost/action')
ws.onopen = function(){
if(this.readyState === 1){
console.log('Connected')
}
}
ws.onmessage = function(ev){
console.log(ev.data)
}
}
init()
ws.send('sbzp');
ws.close()
SSE(Server-Send Event)
建立连接,由后台主动向前端推送内容
var source = null
function init(){
source = new EventSource('http://localtion/test/action.php')
source.onopen = function(){
if(this.readyState === 1){
console.log('Connected')
}
}
source.onmessage = functino(ev){
console.lo(ev.data)
}
source.onerror = function(){
console.log('err')
}
}
init()
source.clos()