Web 页面之间传递参数的方法有很多种,下面列出一些常见的方法以及它们的代码示例。
一、前端直接传递参数
// 发送参数 const params = {id: 123, name: 'Alice'}; const url = `http://example.com/page?${new URLSearchParams(params)}`; window.location.href = url; // 接收参数 const searchParams = new URLSearchParams(window.location.search); const id = searchParams.get('id'); const name = searchParams.get('name');
2、URL hash传递:通过 URL 的 hash 值来传递参数。例如,http://example.com/#/page?id=1可以传递一个名为id的参数。可以通过location.hash来获取和解析hash值中的参数。
// 发送参数 const id = 123; window.location.hash = `#id=${id}`; // 接收参数 const searchParams = new URLSearchParams(window.location.hash.substring(1)); const id = searchParams.get('id');
3、URL 路径传递:通过 URL 的路径参数来传递参数。例如,/users/:id可以传递一个名为id的参数。可以通过路由框架(如 React Router)来解析路径参数。
// 发送参数 const id = 123; window.location.href = `http://example.com/page/${id}`; // 接收参数 const id = parseInt(window.location.pathname.split('/').pop());
4、JavaScript 变量:通过 JavaScript 变量来传递参数。可以在不同的页面之间共享全局变量,或者在一个页面内使用模块化开发来传递参数。
// 发送参数 const id = 123; window.myGlobalId = id; // 接收参数 const id = window.myGlobalId;
5、Cookie:通过在浏览器中存储 Cookie 来传递参数。可以通过document.cookie来读取和设置 Cookie。
// 发送参数 document.cookie = 'id=123; path=/'; // 接收参数 const cookies = document.cookie.split(';').map(cookie => cookie.trim().split('=')); const id = cookies.find(cookie => cookie[0] === 'id')[1];
6、Web 存储:过 HTML5 的localStorage或sessionStorage来在浏览器中存储数据。可以通过localStorage.getItem()和localStorage.setItem()等方法来读取和设置存储的值。
// 发送参数 localStorage.setItem('id', 123); // 接收参数 const id = localStorage.getItem('id');
7、自定义事件:通过自定义事件来在不同的组件之间传递数据。可以通过CustomEvent对象来定义和触发自定义事件,通过element.dispatchEvent()方法来触发事件。
// 发送参数 const event = new CustomEvent('myEvent', {detail: {id: 123, name: 'Alice'}}); document.dispatchEvent(event); // 接收参数 document.addEventListener('myEvent', event => { const {id, name} = event.detail; });
二、后端间接传递参数
9、WebSocket:通过 WebSocket 协议在浏览器和服务器之间实时传递数据。可以使用 WebSocket API 来建立 WebSocket 连接,并通过WebSocket.send()方法来发送数据。
// 发送参数 const id = 123; const ws = new WebSocket('ws://example.com'); ws.onopen = () => ws.send(JSON.stringify({id})); // 接收参数 const ws = new WebSocket('ws://example.com'); ws.onmessage = event => { const {id} = JSON.parse(event.data); };
10、Fetch API:通过 Fetch API 发送 HTTP 请求,并通过请求的 body 传递数据。可以使用fetch()方法来发送请求,并通过body参数传递数据。
// 发送参数 const params = {id: 123, name: 'Alice'}; fetch('http://example.com/page', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(params) }); // 接收参数 const body = await fetch('http://example.com/page').then(res => res.json()); const {id, name} = body;
11、AJAX:通过 XMLHttpRequest 对象发送异步 HTTP 请求,通过请求的参数传递数据。可以通过XMLHttpRequest.send()方法发送请求,通过XMLHttpRequest.onreadystatechange事件监听请求的状态变化。
// 发送参数 const xhr = new XMLHttpRequest(); xhr.open('POST', 'http://example.com/page'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.responseText); } }; const params = {id: 123, name: 'Alice'}; xhr.send(JSON.stringify(params)); // 接收参数 const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/page'); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { const {id, name} = JSON.parse(xhr.responseText); } }; xhr.send();