让我们说我要求用户(在我的本地机器上)输入他们的电子邮件地址以报名抽奖。
<!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
等中。)
答案 0 :(得分:4)
如果没有服务器,您将从JavaScript获得的唯一持久性是通过cookie,本地存储或客户端数据库方法之一。 (有一些方法可以将数据写入文件,但它们通常比这些简单案例的价值更麻烦。)
最简单的是local storage。这将保留用户输入的所有电子邮件的逗号分隔字符串:
if (!localStorage.emails)
localStorage.emails = email;
else
localStorage.emails += ',' + email;
然后在后续的网页访问中,您可以检索用户通过localStorage.emails
变量输入的电子邮件。
答案 1 :(得分:1)
在您的代码中,您根据我的理解进行了细微更改
<!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
答案 2 :(得分:0)
正如我在评论中提到的,您可以使用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>
<强> DEMO 强>