本博客整理了两种方式从一个页面层向另一个页面层传递参数。
一. 通过cookie方式
1. 传递cookie页面的html,此处命名为a.html
请输入用户名和密码:
1
2
3
4
5
|
<input id=
"userName"
type=
"text"
/>
<input id=
"passwords"
type=
"password"
/>
<button id=
"btn"
>设置</button>
<button onclick=
"login()"
>传递cookie</button>
<button onclick=
"deletecookie()"
>删除</button>
|
2.a.html的js代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//设置cookie
var
setCookie =
function
(name, value, day) {
//当设置的时间等于0时,不设置expires属性,cookie在浏览器关闭后删除
var
expires = day * 24 * 60 * 60 * 1000;
var
exp =
new
Date();
exp.setTime(exp.getTime() + expires);
document.cookie = name +
"="
+ value +
";expires="
+ exp.toUTCString();
};
//删除cookie
var
delCookie =
function
(name) {
setCookie(name,
' '
, -1);
};
//传递cookie
function
login() {
var
name = document.getElementById(
"userName"
);
var
pass = document.getElementById(
"passwords"
);
setCookie(
'userName'
,name.value,7)
setCookie(
'password'
,pass.value,7);
location.href =
'b.html'
}
function
deletecookie() {
delCookie(
'userName'
,
' '
,-1)
}
|
3. 接受cookie的页面,此处定义为b.html
1
|
<button onclick=
"getcookie()"
>获取</button>
|
4. b.html的js代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//获取cookie代码
var
getCookie =
function
(name) {
var
arr;
var
reg =
new
RegExp(
"(^| )"
+ name +
"=([^;]*)(;|$)"
);
if
(arr = document.cookie.match(reg)){
return
arr[2];
}
else
return
null
;
};
//点击获取按钮之后调用的函数
function
getcookie() {
console.log(getCookie(
"userName"
));
console.log(getCookie(
"password"
))
}
|
二. 通过url传递参数的方式
该案例也是从a.html向b.html页面传递参数
1. a.html的代码
1
2
|
<input type=
"text"
value=
"猜猜我是谁"
>
<button onclick=
"jump()"
>跳转</button>
|
2.点击跳转按钮可以将input标签的value值传递到b.html
1
2
3
4
|
function
jump() {
var
s = document.getElementsByTagName(
'input'
)[0];
location.href=
'7.获取参数.html?'
+
'txt='
+ encodeURI(s.value);
}
|
3. b.html中的代码
1
2
3
4
5
6
7
|
<div id=
"box"
></div>
var
loc = location.href;
var
n1 = loc.length;
var
n2 = loc.indexOf(
'='
);
var
txt = decodeURI(loc.substr(n2+1,n1-n2));
var
box = document.getElementById(
'box'
);
box.innerHTML = txt;
|
三.通过localStorage
通过localStorage传递参数类似cookie。但是要注意:要访问一个localStorage对象,页面必须来自同一个域名(子域名无效),使用同一种协议,在同一个端口上。
1. a.html中的js文件
1
2
3
4
|
//将localStorage传递到哪个页面
location.href =
'b.html'
//设置localStorage
window.localStorage.setItem(
'user'
,
'haha'
);
|
2.b.html中的文件
1
2
3
4
5
|
<button onclick=
"getcookie()"
>获取</button>
function
getcookie() {
//获取传递过来的localStorage
console.log(window.localStorage.getItem(
'user'
))
}
|