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

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解密。

猜你喜欢

转载自blog.csdn.net/qq_35508162/article/details/81407094
今日推荐