兩種方式從一個頁面層向另一個頁面層傳遞參數。


本博客整理了兩種方式從一個頁面層向另一個頁面層傳遞參數。

一. 通過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' ))
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM