Web前端实现界面间传值的几种方式

在一个web项目中,会有大量的界面。有很多功能是必须要向后台发送请求才能实现的,而界面间传值可以减少不必要的、重复的发送请求操作,从而减轻后台的负担。

第一种方式:利用缓存(cookie)

假如有A, B 两个界面,要把A的值传给B
首先两个界面中都得引入cookie的原生JS。我直接用网页的了。

<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>

A页的代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>注册</title>
		<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
		<script type="text/javascript" src="js/jquery-1.4.3.js"></script>
		<script type="text/javascript">
			$(function(){
				localStorage.setItem('the_cookie','value');
				//console.log(localStorage.getItem('the_cookie'));
			});
			
			function f1(){
		       		var w = document.getElementById("n1").value;
		         	var e = document.getElementById("s1").value;
		         	localStorage.setItem("name",w);
		         	localStorage.setItem("password",e);
		} 
			
		</script>
	</head>
	<body>
		<form>
	  	<p>name:</p>
	    <input id="n1" name="name" type="text" value=""/>
	    <p>password:</p>
	    <input id="s1" name="password" type="password" value=""><br>
	    <input name="button" type="button" value="Register" onclick="f1()" >
	    <a href="word.html">点击返回登录</a>
    	</form>
	</body>
</html>

然后在B页的JS中接收一下就行了

$(function(){
	var yy = localStorage.getItem("name");
    	var xx = localStorage.getItem("password");
	console.log("用户名"+yy);
	console.log("密码"+xx);
});

第二种方法:利用url参数传递

A界面,发送数据

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		<form name="frm" method="get" action="my_index.html" onsubmit="return foo()">
			<input name="id" value="" index="haha" />
			<input type="submit" />
		</form>
		<script type="text/javascript">
			function foo(){
				return true;
			}
		</script>
	</body>
</html>

B页面接收

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			//通过window.location.href(当前url)接收
			var str = window.location.href;
			//对当前url进行字符串分割,变成字符串数组
			var arrStr = window.location.href.split("=");
			var mystr = window.location.href.split("=")[1];
			console.log("接收到了"+mystr);
		</script>
	</body>
</html>

此人才疏学浅,知道多少说多少,大家在实用时遇到问题的话多多沟通学习。

  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值