gpt4 book ai didi

javascript - 使用js延迟函数时使用ISSET验证表单

转载 作者:行者123 更新时间:2023-11-30 19:52:35 25 4
gpt4 key购买 nike

我正在尝试验证是否使用 isset() 发送了正确的表单,但是当应用 javascript 延迟时此验证不是 TRUE。怎么会?检查是否通过 POST 方法提交了正确的表单的最佳方法是什么?请参阅下面的代码。也许隐藏字段可以解决问题,但我真的很想知道为什么下面的代码没有通过。

<script type="text/javascript">
window.addEventListener('load', function onload(){
var ccform = document.getElementById('cc_form');
if(ccform){
ccform.addEventListener('submit', function before_submit(e){
setTimeout(function wait(){
// After waiting, submit the form.
ccform.submit();
}, 2000);

// Block the form from submitting.
e.preventDefault();
});
}
});
</script>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cc_form_submit'])) {
//Send the form
//Not working
echo 'ready to send!';
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Send the form
//Working
echo 'ready to send without ISSET!';
}
?>
<form action="" method="post" class="cc_form" id="cc_form">
<button class="cc_form_submit" type="submit" name="cc_form_submit">Send!</button>
</form>

最佳答案

在您的示例中,有很多可能的解决方案:

解决方案一:

您可以在表单中使用隐藏值,然后在 isset() 中检查该值方法如:

<form method="post">
<input type="hidden" name="form1" />
<button>Submit</button>
</form>

<form method="post">
<input type="hidden" name="form2" />
<button>Submit</button>
</form>

<?php
if(isset($_POST['form1'])){
// do somthing
}

if(isset($_POST['form2'])){
// do somthing
}
?>

解决方案 2:

您可以使用输入类型提交而不是 <button>喜欢:

<form method="post">
<input type="submit" name="form1">
</form>

<form method="post">
<input type="submit" name="form2">
</form>

<?php
if(isset($_POST['form1'])){
// do somthing
}

if(isset($_POST['form2'])){
// do somthing
}
?>

解决方案 3:

您可以对多个 <form> 使用不同的操作喜欢:

<form method="post" action="form1.php">
</form>

<form method="post" action="form2.php">
</form>

编辑:

根据您的评论不知道为什么 if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cc_form_submit'])) { 不起作用。

它不起作用,因为您正在使用 name=属性为 <button> ,在这种情况下,解决方案 2 适合您。

关于javascript - 使用js延迟函数时使用ISSET验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54329196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com