html使用js两个页面的值传递

本文介绍了一种通过URL参数在不同HTML页面间传递数据的方法。详细解释了如何在A.html页面设置带有参数的链接,B.html页面如何接收并处理这些参数,并最终在C.html页面展示这些值的过程。此外还提供了两种解决中文参数乱码问题的方案。

A.html

<body>
         <a href="B.html?name=li&time=morning">传递按钮</a>
    </body>

B.html

<body>
        <a href="C.html" id="bbb">传递按钮</a>  

<script>
function GetRequest() {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

var Request = new Object();
    Request = GetRequest();
    var a, b;
    a = Request['name'];
    b = Request['time'];   
    document.getElementById("bbb").href = 'C.html?name='+a+'&time='+b;//修改href,继续传递
</script>
    </body>

C.html

<body>
        <p id="ccc"></p>

        <script>
            var s = location.search.substring(1); //这个就是页面?后面的内容,自己处理一下
            //            alert(s);
            var theRequest = new Object();
            //            name=li&time=morning
            ss = s.split("&"); //从'&’ 将两个元素分开
            //            alert(ss)
            //            console.log(ss)
            for(var i = 0; i < ss.length; i++) {
                theRequest[ss[i].split("=")[0]] = unescape(ss[i].split("=")[1]);
            }
            console.log(theRequest)
            var a = theRequest['name'];
            var b = theRequest['time'];
            console.log(a)
            console.log(b)
            document.getElementById("ccc").innerHTML=a;
//            document.getElementById("ccc").write(b);
        </script>
    </body>

注:如若是中文传值时,会产生乱码:解决如下:

方法一escape和unescape:主要使用与a标签之间的网页传值

<a href="detail.html?name='+escape(name)+'" target="blank" title="' + name + '">

另一html文件

<script>
            var s = location.search.substring(1); //这个就是页面?后面的内容,自己处理一下
            var theRequest = new Object();
            ss = s.split("&"); //从'&’ 将两个元素分开
            for(var i = 0; i < ss.length; i++) {
                theRequest[ss[i].split("=")[0]] = unescape(ss[i].split("=")[1]);
            }
            console.log(theRequest)
            var a = theRequest['name'];
            console.log(a)
            document.getElementById("name").innerHTML=a;
        </script>

方法二:urlencode进行加密,urldecode解密。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值