最近在做html网站前端开发,其中就用到了两个静态页面之间需要传值的问题。本片文章总结了通过url参数传值、通过cookies传值等方式实现的具体方式,附代码。
方法一:get请求,通过url中携带参数传值
例子:
a.html文件内容
<a href="b.html?test=1&id=2">b.html</a>
b.html文件内容
<script> alert(window.location.search); </script>
b.html文件通过window.location.search即可获得?test=1&id=2这部分数据,然后再通过js相关正则表达式函数或者split()函数处理这个字符串值即可获得传递的参数,见下图:
方法二:使用本地存储的cookies,保存值,来回传递数据。
post2.html将数据保存在cookie文件中,代码如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>post2</title> <script> function click1(){ var name = document.getElementById("name").value; var pwd = document.getElementById("pwd").value; document.cookie = "name:" + name + "&pwd:" + pwd; location.href="get2.html"; } /* 关于cookie,要特别处理传过来的字符串,其次,还有些浏览器不支持cookie的,但目前来说,一般浏览器都支持cookie */ </script> </head> <body> 名字:<input type="text" id="name"/> 密码:<input type="text" id="pwd"/> <input type="button" onclick="click1()" value="提交:"/> </body> </html>
get2.html 通过js获得cookie中的值,代码如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>get2</title> <script> function click1(){ var params= document.cookie; var pa = params.split("&"); var s = new Object(); for(var i = 0; i < pa.length; i ++){ s[pa[i].split(":")[0]] = pa[i].split(":")[1]; } document.getElementById("name").value =s.name; document.getElementById("pwd").value = s.pwd; } </script> </head> <body> 名字:<input type="text" id="name"/> 密码:<input type="text" id="pwd"/> <input type="button" onclick="click1()" value="获取:"/> </body> </html>
方法3:localStorage
post3.html保存数据,代码:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>post3</title> <script> function click1(){ var name = document.getElementById("name").value; var pwd = document.getElementById("pwd").value; localStorage.setItem("name",name); localStorage.setItem("pwd",pwd); location.href="get3.html"; } </script> </head> <body> 名字:<input type="text" id="name"/> 密码:<input type="text" id="pwd"/> <input type="button" onclick="click1()" value="提交:"/> </body> </html>
get3.html获得传递过来的参数值,代码:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>get3</title> <script> function click1(){ document.getElementById("name").value = localStorage.getItem("name"); document.getElementById("pwd").value = localStorage.getItem("pwd"); } /* 方便简单, 但是要考虑浏览器的版本支持 */ </script> </head> <body> 名字:<input type="text" id="name"/> 密码:<input type="text" id="pwd"/> <input type="button" onclick="click1()" value="获取:"/> </body> </html>
这种方法简单有效,同时还不需要字符串解析。非常的有意思。但是要注意浏览器的版本支持,所以在使用前请判断是否支持。
如果需要传递大数值不多的话可以使用方法1:url中带参数、方法3,多的话建议使用方法2:cookies方法。
更多相关推荐
版权保护:本文《html静态页面间传递数据值的几种方式》由<我爱分享>原创,转载请保留链接:http://shuidi365.cn/site/98.html
此博客主要用来分享、推荐自己日常、学习过程中感觉比较实用的经验、IT技术和一些比较好的资源(各种软件、各种开发手册、各种学习资料、各种视频教程等),希望对大家有所帮助,有问题请留言,欢迎来交流,联系QQ邮箱/微信:342807450