JavaScript 使用链接跳转传递数组对象数据类型的方法


在前端有的时候会需要用链接进行传递参数,基本数据类型的传递还是比较简单的,但是如果要传递引用数据类型就比较麻烦了,虽然使用sessionStorage或者localStorage也可以实现页面传参,但是如果是多端进行传参就不能够实现了,比如说在pc端的一个页面生成了一个二维码,需要手机端去打开浏览,但是手机进入可能会需要向后台请求数据,这个时候就会用到参数,下面给大家分享一个页面之间传递引用数据类型的方法,这个也是可以实现二维码传参的:

首先了解一下正常传递基本数据类型

跳转传参是指在页面跳转时,将部分数据拼接到URL路径上,一并跳转到另一个页面上,这里要注意拼接,返回的会是字符串的形式:

JavaScript 跳转页面方法

window.location.href = 'http://www.baidu.com'; // 通过改变location.href来实现页面跳转 常用
window.location.replace('http://www.baidu.com'); // 通过location.replace替换当前页面路径来实现页面跳转
window.location.assign('http://www.baidu.com'); // 通过location.assign加载新文档来实现页面跳转

注意区别:
href是在当前页面进行跳转,浏览器的后退按钮还是可以点击的
replace则是将当前页面的路径进行了替换,浏览器的后退按钮不会在生效
使用location.assign()方法传递的URL必须是绝对路径,否则会导致页面无法重定向的情况,而且在IE8以下版本中,如果URL的长度超过了2083个字符,调用location.assign()方法将会失败,在一些浏览器中,如果在页面加载完成后对location.assign()进行调用,可能会导致页面闪烁现象

JavaScript 路由传递参数

使用路由传参可以参考了解浏览器的地址链接,‘?’ 后边的就是参数,多个参数用 ‘&’ 分割

// 单传值
window.location.href = 'http://www.baidu.com?1';
window.location.replace('http://www.baidu.com?1');
window.location.assign('http://www.baidu.com?1');
// 传键值对
window.location.href = 'http://www.baidu.com?id=1';
window.location.replace('http://www.baidu.com?id=1');
window.location.assign('http://www.baidu.com?id=1');
// 多个参数
window.location.href = 'http://www.baidu.com?id=1&value=asdf';
window.location.replace('http://www.baidu.com?id=1&value=asdf');
window.location.assign('http://www.baidu.com?id=1&value=asdf');

这些只是简单的数据类型,如果需要传递引用数据类型或者数据中存在汉字,需要先使用JSON.stringify() 方法将数据进行转换

let str = '张三';
let json_str = JSON.stringify(str);// 转换为json格式
//
window.location.href = encodeURL('http://www.baidu.com?id=1&value=' + json_str);
//
window.location.replace(encodeURL('http://www.baidu.com?id=1&value=' + json_str));
//
window.location.assign(encodeURL('http://www.baidu.com?id=1&value=' + json_str));

JavaScript 路由接收参数

let str = window.location.search; //获取链接中传递的参数
let params = str.substring(str.indexOf("=") + 1);
dataJson = JSON.parse(decodeURI(params));
console.log("dataJson :", dataJson);

// 或者
let data = new URLSearchParams(window.location.search);
console.log(JSON.parse(data.get('id')));
console.log(JSON.parse(data.get('value')));

这里推荐使用第二种方法,更为简便

传递对象

上边已经将方法说明过了,下面的是示例:
页面跳转demo:

let arr = {
    
    
	name: 'zz',
	sex: '男',
	age: 11
}
let datajson = JSON.stringify(arr);
// 跳转页面,这里需要大家自己将页面路径进行修改
window.location.href = encodeURI('accept.html?datajson=' + datajson);

接收参数demo:

let dataJson;
let str = window.location.search; //获取链接中传递的参数
let arr = str.substring(str.indexOf("=") + 1);
dataJson = $.parseJSON(decodeURI(arr));
console.log("dataJson :", dataJson);
// 或者

let data = new URLSearchParams(window.location.search);
console.log(JSON.parse(data.get('datajson')));

效果:

接收参数打印效果图

猜你喜欢

转载自blog.csdn.net/qq_68862343/article/details/131572070