当前位置:首页 > JavaScript

js实现通信

2026-02-01 02:37:20JavaScript

JavaScript 实现通信的方法

JavaScript 提供了多种方式实现不同场景下的通信,包括浏览器与服务器、页面间、跨域等场景。

原生 AJAX 通信

使用 XMLHttpRequest 对象实现异步数据请求:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

Fetch API

现代浏览器支持的更简洁的异步请求方式:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

WebSocket 实时通信

建立持久连接实现双向实时通信:

const socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = () => socket.send('Hello Server!');
socket.onmessage = event => console.log(event.data);

postMessage 跨窗口通信

实现不同窗口/iframe 间的安全通信:

// 父窗口
iframe.contentWindow.postMessage('hello', 'https://child-origin.com');

// 子窗口
window.addEventListener('message', event => {
  if (event.origin === 'https://parent-origin.com') {
    console.log(event.data);
  }
});

Server-Sent Events (SSE)

服务器向客户端推送单向事件流:

const eventSource = new EventSource('/updates');
eventSource.onmessage = event => {
  console.log('New update:', event.data);
};

WebRTC 点对点通信

实现浏览器间直接数据传输(适合视频聊天等场景):

// 需要先建立信令服务器交换SDP信息
const pc = new RTCPeerConnection();
pc.onicecandidate = event => {
  if (event.candidate) {
    // 通过信令服务器发送候选地址
  }
};
pc.ondatachannel = event => {
  const channel = event.channel;
  channel.onmessage = event => console.log(event.data);
};

每种通信方式适用于不同场景,选择时需考虑浏览器兼容性、实时性要求、安全限制等因素。现代应用通常结合使用多种方式,例如用 WebSocket 实现实时通知,用 Fetch 处理常规 API 请求。

js实现通信

标签: 通信js
分享给朋友:

相关文章

js 实现vue

js 实现vue

实现 Vue 的核心功能 在 JavaScript 中实现 Vue 的核心功能需要模拟数据绑定、虚拟 DOM 和响应式系统。以下是一个简化版的实现思路: 响应式系统 通过 Object.defin…

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

vue实现串口通信

vue实现串口通信

Vue 实现串口通信的方法 在 Vue 项目中实现串口通信,通常需要借助浏览器提供的 Web Serial API 或第三方库。以下是几种常见的实现方式: 使用 Web Serial API We…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https:/…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document…

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以…