【问题标题】:Validate form with ISSET when using js delay function使用 js 延迟函数时使用 ISSET 验证表单
【发布时间】:2019-01-23 14:14:04
【问题描述】:

我正在尝试验证是否使用 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>

【问题讨论】:

  • 您想在delay(2000) 之后使用jquery 提交您的表单吗?自动
  • 没有?点击提交按钮后。目前我在同一页面上有多个表单,我想对正在使用 $_POST 方法处理的正确表单进行额外验证。
  • 如果您有多个表单,请使用操作。或ajax
  • 或使用隐藏值并签入isset()
  • 或者你可以使用 input type="button" 而不是

标签: javascript php forms post isset


【解决方案1】:

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

解决方案 1:

您可以在表单中使用隐藏值,然后在 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:

您可以使用输入类型提交代替&lt;button&gt;,例如:

<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:

您可以对多个&lt;form&gt; 使用不同的操作,例如:

<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= 属性与 &lt;button&gt; 一起使用,在这种情况下,解决方案 2 将适合您。

【讨论】:

  • 谢谢,我知道这些解决方案只是不知道为什么 if ($_SERVER['REQUEST_METHOD'] == 'POST' &amp;&amp; isset($_POST['cc_form_submit'])) { 不起作用。
  • @RobbTe: 因为
猜你喜欢
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 2021-08-25
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
相关资源
最近更新 更多