js教程

同域两个网页JS传值示例

精准像素 2022-03-18 人阅读

first.html网页,通过a.js向jieshou.html传值,主要通过域名传值接受方法

<!DOCTYPE html>
<html>
        <head>
                <meta charset="UTF-8">
                <title>第一个网页</title>
        </head>
        <script type="text/javascript" src="a.js"></script>
        <body
                <form name="form1" action="jieshou.html" method="post">
                        <h3>传值</h3>
                        <input class="text_1" type="text" name="wd" id="text_1" value=""/>
                        <input type="submit" name="sousuo" id="submit_s" value="提交"/>
                </form>
        </body>
</html>

a.js文件

function sub() {
        var str = "" + document.getElementById('text_1').value;
        var url = "jieshou.html?wd=" + encodeURI(str);
        location.href = url;
}

jieshou.html接收页面

<!DOCTYPE html>
<html>
        <head>
                <meta charset="UTF-8">
                <title>接收显示</title>
        </head>
        <body>
                <form name="form2" action="">
                        <input name="xianshi" id="text_2" type="text" />
                </form>
                <script type="text/javascript">
                        var loc = location.href;
                        loc = decodeURI(loc);
                        var n1 = loc.length; //地址的总长度  
                        var n2 = loc.indexOf("=");
                        if (n2 > 0) {
                                var id = loc.substr(n2 + 1, n1 - n2);
                                document.getElementById("text_2").value = id;
                        }
                </script>
        </body>
</html>