两个 html 页面之间传数据

来源:互联网 发布:随手记账软件 编辑:程序博客网 时间:2024/05/21 02:25

在两个 html 页面之间传数据小示例

page1:

<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>page1</title>      </head>  <body>      <input type="text" value="要传的值是a" id="testInput" >      <input type="button" value="点击" onclick="toPage2()" >     <script>          function toPage2(){              var inputVal = document.getElementById("testInput").value;              window.location.href = encodeURI("page2.html?value=" + inputVal);               // 传的数据中包含中文,所以用 encodeURI() 将链接编码        }      </script>  </body>  </html>   

page2:

<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>page2</title>     </head>  <body>          <script>          var thisURL = decodeURI(document.URL);   // 获取当前页面的 url, 用decodeURI() 解码        var getVal = thisURL.split('?')[1];        var showVal= getVal.split("=")[1];         alert(thisURL);                          // 结果:page2.html?value=要传的值是a        alert(getVal);                           // 结果:value=要传的值是a        alert(showVal);                          // 结果:要传的值是a    </script>  </body>  </html> 

注意:

如果传的数据中有中文,会出现乱码,解决办法如下:
在 page1 页面中用 encodeURI 将 url 编码, 在 page2 页面中用 decodeURI 将 url 解码即可。

原创粉丝点击