javascript 提交今天的日期作为隐藏的表单输入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15103890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:30:46  来源:igfitidea点击:

Submit today's date as a hidden form input value

javascriptformsdate

提问by user2066907

I need to send the current date in this format yyyymmdd via a hidden form input field.

我需要通过隐藏的表单输入字段以这种格式 yyyymmdd 发送当前日期。

I have the date formatted as I want with this javascript

我用这个 javascript 按我想要的格式设置了日期

function getDate()
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = yyyy+mm+dd;
}

And this is my form input field

这是我的表单输入字段

<input type="hidden" name="startdate" onload="this.value = getDate();"/>

I've tried several ways to assign the date above to my var startdate and send it to the server, without any success.

我尝试了几种方法将上面的日期分配给我的 var startdate 并将其发送到服务器,但没有任何成功。

Can you show me how to pass the date to my hidden input field when the page loads?

你能告诉我如何在页面加载时将日期传递给我的隐藏输入字段吗?

And I'm wondering if this posses any problems with regards to security and hackers?

我想知道这是否对安全和黑客有任何问题?

Thanks for your help

谢谢你的帮助

采纳答案by PSR

<input type="hidden" name="startdate" id="todayDate"/>
<script type="text/javascript">
function getDate()
{
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm}
    today = yyyy+""+mm+""+dd;

    document.getElementById("todayDate").value = today;
}

//call getDate() when loading the page
getDate();
</script>

回答by Luke

If you are using the date for some kind of validation then for security you would be much better off using server side scripting; that way the client can't spoof dates.

如果您使用日期进行某种验证,那么为了安全起见,您最好使用服务器端脚本;这样客户就不能欺骗日期。

Furthermore, you shouldn't use an <input>, even if you used the server side to generate the date, because you could still spoof the time using Firebug or many other web developer tools. The HTTP POST (or whatever) submitted could contain spoofed data. In the end nothing is 100% secure though.

此外,<input>即使您使用服务器端生成日期,也不应该使用,因为您仍然可以使用 Firebug 或许多其他 Web 开发人员工具来欺骗时间。提交的 HTTP POST(或其他)可能包含欺骗数据。但最终没有什么是 100% 安全的。