window.location.href跳转传参并接收参数

最近做H5页面之间跳转以及带有参数的传递,下边就让我们一起来练习一下吧!

window.location.href = "buyOil.html?userId="+ res.userId;
buyOil.html    这是跳转路径的地址
res.userId是我们传过去的参数,在这里我们模拟res.userId是2,所以就变成了
window.location.href = "buyOil.html?userId="+ 2;

我们在buyOil.html这里边接受这个参数

				function GetRequest() {
					var url = location.search; //获取url中"?"符后的字串
					var theRequest = new Object();
					if (url.indexOf("?") != -1) {
						var str = url.substr(1);
						strs = str.split("&");
						for (var i = 0; i < strs.length; i++) {
							theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
						}
					}
					return theRequest;
				}
				console.log(GetRequest().userId);  //2

这时候打印出来的结果就是我们传过来的参数,就是2

  • 6
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
window.location.href可以用于页面跳转并传递参数。通过将参数添加到URL中的查询字符串中,可以在目标页面中获取这些参数。一种常见的方式是在URL中使用问号传参的方式,例如:window.location.href = "./punch/clock_frm.html?modFlag=" + modFlag + "&role=" + role。这样,modFlag和role参数的值就会被传递到目标页面中。在目标页面中,可以使用JavaScript解析URL中的查询字符串来获取这些参数。一个常见的方法是使用location.search来获取URL中的查询字符串部分,然后使用split和for循环来解析参数值。例如: var url = location.search; //获取url中"?"符后的字串 (’?modFlag=business&role=1’) var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); var strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]); } console.log(theRequest); } 这样,theRequest对象就包含了传递的参数值。如果需要解决中文乱码问题,可以使用encodeURI对中文内容进行编码,例如:window.location.href = 'aaa.html?Unit=' + encodeURI(encodeURI(中文内容))。在接收页面中,可以使用decodeURI对URL进行解码,例如:decodeURI(window.location.href)。这样,就可以正确地传递和接收带有中文的参数值了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [转载--window.location.href传参/传值汇总](https://blog.csdn.net/weixin_47382065/article/details/120264692)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [记一次window.location.href传对象问题](https://blog.csdn.net/w979000397/article/details/123728766)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值