当前位置: 首页 > 工具软件 > JSON 2 HTML > 使用案例 >

HTML页面之间传递JSON两种方式

徐洋
2023-12-01

a.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="js/jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/canshu.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<button>跳转</button>
	</body>
	<script type="text/javascript">
		var item = {
			name: "刘备",
			age: 50,
			sex: "男",
		}


		// ##############   localStorage 存储
		localStorage.setItem("item", JSON.stringify(item))

		// #############  url后传递json
		$("button").click(function() {
			window.location.href = "b.html?item=" + escape(JSON.stringify(item))
		})
	</script>
</html>

b.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/canshu.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<button>返回</button>
		<span></span>
	</body>
	<script type="text/javascript">
		$("button").click(function() {
			history.back();
		})
		var a = request.getUrlParam("item")
		var b = JSON.parse(unescape(a));
		$("span").text(b.age)
		
		
		
		// #########  localStorage读取  JSON 
		JSON.parse(localStorage.getItem("item"))
	</script>
</html>

js

//获取url中的参数
var request={
	getUrlParam:function(name){
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
		var r = window.location.search.substr(1).match(reg); //匹配目标参数
		if (r != null) return unescape(r[2]);
		return null; //返回参数值
	},
}

 

 类似资料: