js 接收后台数据推送

本文主要探讨了前端如何实现数据推送,包括基于HTTP长连接的Comet技术、使用WebSocket建立稳定连接进行双向通信,以及SSE(Server-Send Event)允许服务器单向推送内容的方法。通过jQuery、axios和原生JavaScript的示例,阐述了这些技术的实现细节。

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

* 本文章仅包含数据推送,前端部分内容 *

Comet

基于HTTP长连接的服务器推送技术

就是前端向后台发送一个请求,后台进行一个死循环,一直向前端发送信息.

  1. 使用jQuery
function conn(){
    $.ajax({
        url:'/action'
        type:'get',
        dataType:'json',
        success:function(data){
            console.log(data)
            conn()
        }
    })
}
conn()
  1. 使用axios
function conn(){
    axios.get('/action').then(response=>{
        console.log(response.data)
        conn()
    }).catch(err){
        console.log(err)
    }
}
conn()
  1. 使用原生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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值