首页 > 其他分享 >Web 页面之间传递参数

Web 页面之间传递参数

时间:2023-02-15 18:33:23浏览次数:40  
标签:Web const 发送 xhr 123 参数 id 页面

Web 页面之间传递参数的方法有很多种,下面列出一些常见的方法以及它们的代码示例。

一、前端直接传递参数

  • 1、URL 参数传递(query string):通过 URL 的查询字符串(即问号后面的参数)将参数传递给页面。可以通过location.searchURLSearchParams对象来获取和解析参数。
// 发送参数
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 的localStoragesessionStorage来在浏览器中存储数据。可以通过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;
});

二、后端间接传递参数

  • 8、表单提交:过表单的提交将表单中的数据传递给后台服务器或其他页面。可以通过form元素的submit方法或XMLHttpRequest对象来实现表单提交。
<!-- 发送参数 -->
<form method="POST" action="http://example.com/page">
  <input type="text" name="id" value="123">
  <input type="text" name="name" value="Alice">
  <button type="submit">提交</button>
</form>

<!-- 接收参数 -->
<?php
$id = $_POST['id'];
$name = $_POST['name'];
?>
  • 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();

 

标签:Web,const,发送,xhr,123,参数,id,页面
From: https://www.cnblogs.com/yuzhihui/p/17124263.html

相关文章

  • idea创建web项目实操
    打开idea,选择createnewproject  直接进入项目页面的小伙伴,点击file--new--project  选择创建空项目作为工作空间,next  选择项目地址,并命名项目  fin......
  • JAVA线上参数设置及常见问题
    常用配置参数jar包启动配置命令java-Xmx8g-Xms8g-XX:+UseG1GC-jar/home/pgcp/pgcp-0.0.1-SNAPSHOT.jartomcat启动配置参数在/bin/catalina.sh中/cygwin=false前......
  • 微信小程序:欢迎页面
    逻辑:打开微信小程序,默认首先展示的是/pages/index/index页面,所以我们的欢迎页面写在index页面中,然后在欢迎页面通过点击跳转到首页/pages/home/index页面,由于首页是tab页......
  • 拦截刷新页面和关闭页面 并不能监听按钮返回的值
    1componentWillMount(){2//拦截判断是否离开当前页面3window.addEventListener('beforeunload',this.beforeunload);4}5componentWillU......
  • BaseServlet抽取以及UserServlet页面路径改写
    BaseServlet抽取减少Servlet的数量,现在是一个功能一个Servlet,将其优化为一个模块一个Servlet,相当于在数据库中一张表对应一个Servlet,在Servlet中提供不同的方法来完成用户......
  • JavaWeb的前期准备
    一、概念1.什么是javaWebJavaWeb指的是,java语言编写的可以通过浏览器访问的程序,统称为JavaWeb,它基于请求和响应。2.什么是请求请求指的是客户端向服务器发送数据,叫请......
  • 给按钮添加js代码,点击按钮后复制页面上的某个文本内容
    你可以通过JavaScript的document.execCommand()方法,结合使用document.createRange()和window.getSelection()方法来实现复制文本的功能。下面是一个例子,当用户点......
  • 15. CTFshow 萌新 web1
    一、代码<html><head><title>ctf.show萌新计划web1</title><metacharset="utf-8"></head><body><?php#包含数据库连接文件include("config.php");#判......
  • 与AI对话 -- 20230215 -- linux 启动参数与控制台
    linux启动参数console=ttyS0,115200n8console=tty0说明console=ttyS0,115200n8:指定系统使用ttyS0(ttyS1、ttyS2以此类推)串口作为主控台,115200n8意思是以115200即......
  • Go实现Web 应用程序
    Go内置有net/http包使用这个http包可以实现Web服务。 通过下面简单的两个函数,就可以搭建一个Web服务,同时该Web服务具有高并发的特性。http.HandleFunc("/favicon......