HTML頁面間之間傳遞數據的兩種方法

常常會有要在兩個頁面中傳遞數據的需求,HTML頁面間傳遞數據的兩種方法:html

方法1,經過URL傳遞,在第二頁面運用location對象的方法獲取;json

方法2,將數據存儲在localStorage中,在第二頁面中讀取。編碼

頁面1的HTML和JS代碼以下:code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
    	<h1>頁面1</h1>	
    </body>
</html>
var student={  //一個json數據
		"name":"gougou",
		"age":2
	}   
	var strStudent=JSON.stringify(student);  //將json轉化爲字符串strStudent。
	localStorage.setItem('key',strStudent);  //對應方法2,將數據存儲在HTML5的localStorage中。

	alert("點擊跳轉到頁面2");
	location.href="location2.html?student="+window.encodeURIComponent(strStudent);  
    //對應方法1,先將json的字符串strStudent進行編碼(不編碼則在頁面2中不能正常獲取),
    //再放進URL裏進行傳遞,再設置location對象的href屬性讓頁面跳轉。

頁面2的HTML和JS代碼以下:htm

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
    	<h1>頁面2:數據傳過來了嗎?</h1>
    	<div id="demo1"></div>
    	<div id="demo2"></div>

    </body>
</html>
window.onload=function (){
		//對應方法1
		var someUrl=location.search; 
        //location對象能夠獲取當前頁面的URL地址,它的search屬性能夠獲取?後面的部分(含?)
		var student1=JSON.parse(window.decodeURIComponent(someUrl.split("=")[1]));  
       //取得=後面的字符串,反編碼後再轉回原來的json對象
		document.getElementById("demo1").innerHTML="方法1傳過來了,我能夠獲取name="+student1.name;

		//對應方法2
		var student2=JSON.parse(localStorage.getItem('key'));
		document.getElementById("demo2").innerHTML="方法2傳過來了,我能夠獲取age="+student2.age;
	}
相關文章
相關標籤/搜索