常常会有要在两个页面中传递数据的需求,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; }