【问题标题】:Pass info from page to page (offline)在页面之间传递信息(离线)
【发布时间】:2014-04-29 15:36:37
【问题描述】:

假设我在页面上有一个输入框。我单击一个按钮,输入中的任何内容都会传输到另一个页面并使用 JavaScript 检索。

Page1 = C:\Documents\page1.html

第1页代码:

    <!DOCTYPE html>
    <html>
    <body>
        <p>Name: <input type="text" id="user_input"</input></p>
        <button onclick="start_page_2()">submit</button>

        <script>
            var start_page_2 = function(){
                contents = document.getElemeentById("user_input").value;
                //code to go to page 2;
                }
        </script>
    </body>
    </html>

Page2 = C:\Documents\page2.html

第2页代码:

    <DOCTYPE html>
    <html>
    <body>
    <h1 id="my_title">empty</h1>
    <script>
        //on load execute this {
            //retrive contents from page1 and save as contents
            //document.getElementById("my_title").innerHTML(contents);
            //}
    </script>
    </body>
    </html>

*请注意,输入将包含空格(如果有帮助的话)。所有有用的答案都会被投票。

【问题讨论】:

  • 你有表单标签,但你没有使用表单。您想在页面之间使用表单或 Javascript 吗?另外,我是否正确假设您的开发机器上没有设置 Web 服务器?
  • 你可以使用 LocalStorage。
  • Cookie 不一定有帮助,因为现代浏览器将每个本地文件视为其自己的不同域。因此,您不能在本地页面(或本地存储)之间共享 cookie。
  • 如果表单标签可以使用,请随时提供帮助。 PS:我可以使用 PHP 做到这一点,但我希望这个离线
  • @Wolfdog - 你的“离线”是什么意思,你使用的是 file:// 协议,这通常不是一个好主意,因为几乎没有任何效果

标签: javascript html forms


【解决方案1】:

你可以只使用 localStorage

第1页

<!DOCTYPE html>
    <body>
        <p>Name: <input type="text" id="user_input"</input></p>
        <button onclick="start_page_2()">submit</button>

        <script>
            var start_page_2 = function(){
                var contents = document.getElementById("user_input").value;
                localStorage.setItem('user', contents);
                window.location.href = 'page2.html';
            }
        </script>
    </body>
</html>

第2页

<DOCTYPE html>
    <body>
        <h1 id="my_title">empty</h1>
        <script>
            var full_name = localStorage.getItem('user');
            document.getElementById("my_title").innerHTML = full_name;
        </script>
    </body>
</html>

这只有在您使用实际的网络服务器来测试您的页面时才有效,并且在 MDN 上有一个适用于旧版浏览器的 polyfill

【讨论】:

  • 难道不是 Chrome 和其他人认为单独的本地 file:// URL 是不同的域吗?您必须使用 --allow-file-access-from-files 启动 Chrome 才能禁用该安全措施。我认为他们正试图防御已安装软件包中的敌对.html 文件。 edit 哎呀,看看你的资格:)
  • 如果在接下来的 5 分钟内没有其他消息弹出,这将是我接受的答案
  • @Pointy - 事实上,在使用 file:// 协议时,localStorage 几乎被阻止,ajax、cookie 等也是如此,并且任何服务器端语言都已被淘汰,这就是我们从不使用 file:// 的原因协议
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 2017-12-23
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
相关资源
最近更新 更多