如何在外部存储javascript变量(没有服务器)的值

How do I store the value of a javascript variable (without a server) externally?

本文关键字:服务器 的值 变量 外部 存储 javascript      更新时间:2023-09-26

假设我要求用户(在我的本地机器上)输入他们的电子邮件地址来注册抽奖活动。

<!DOCTYPE HTML>
<head><title>Raffle</title></head>
<script type="text/javascript">
        var email;
        function foo(){
            email = document.getElementById("Email").value;
            alert(email);
        }
</script>
<body>
<input id="Email" name="Email" type="email">
<input type="Submit" id="submit" name="submit" onclick="foo();">
</body>

小提琴

当用户点击提交时,电子邮件地址会在他们面前弹出。有没有办法同时将变量email存储在外部文件(.php.txt等)

如果没有服务器,你从JavaScript获得的唯一持久性是通过cookie,本地存储或客户端数据库方法之一。(有一些方法可以将数据写入文件,但对于这种简单的情况,它们通常比它们的价值更麻烦)。

最简单的是本地存储。这将保留用户输入的所有电子邮件的逗号分隔字符串:

if (!localStorage.emails)
    localStorage.emails = email;
else
    localStorage.emails += ',' + email;

然后在后续页面访问中,您可以检索用户通过 localStorage.emails 变量输入的电子邮件。

在您的

代码中,据我所知,您进行了细微的更改

<!DOCTYPE HTML>
<head><title>Raffle</title></head>
<script type="text/javascript">
    var email;
    function foo(){
        email = document.getElementById("Email").value;
        /* this function stored your email variable to another php page as a variable name php_email */
        $.post('anyphppagename.php',php_email:email,function(){
        });
        alert(email);
    }
</script>
<body>
<input id="Email" name="Email" type="email">
<input type="Submit" id="submit" name="submit" onclick="foo();">
</body>

以另一种方式,您可以在jQuery脚本中向用户显示此值

<script type="text/javascript">
var email;
function foo(){
email = document.getElementById("Email").value;
alert(email);
$("#getemail").html(email);
$("#getemail").css("display","block");
}
</script>
<body>
<span id="getemail" style="display:none;"></span>
<input id="Email" name="Email" type="email">
<input type="Submit" id="submit" name="submit" onclick="foo();">
</body>


hopefully it may help you

正如我在评论中提到的,您可以使用localStorage单个浏览器中保存值。

如果要存储电子邮件地址列表,最好的办法是将它们存储为数组,并将其序列化到 localstorage 中

<!DOCTYPE HTML>
<head><title>Raffle</title></head>
<script type="text/javascript">
        function storeEmail(email) {
            var addressesSerialized = localStorage.emails || "[]";
            var addresses = JSON.parse(addressesSerialized);
            addresses.push(email);
            localStorage.emails = JSON.stringify(addresses);
        }
        function foo(){
            var email = document.getElementById("Email").value;
            alert(email);
            storeEmail(email);
        }
</script>
<body>
<input id="Email" name="Email" type="email">
<input type="Submit" id="submit" name="submit" onclick="foo();">
</body>

演示