PHP:回应表单提交的输入

时间:2015-08-22 18:09:56

标签: javascript php html forms

我有一个包含一个文本字段的表单。现在,我试图在提交表单后回显输入的内容。这是我的相同代码:

if (!preg_match("/^[a-zA-Z ]*$/",$_POST['name']) || strlen($_POST['name']) < 2) {
  $errors['name'] = 'Please put in your name.';
}

上面的代码在PHP文件中。但是,在提交表单时没有任何回应。该函数会按预期调用,因为我在调试时尝试回显自定义消息。但是,当我尝试回显<script> function postResultss() { document.write("<?php echo ($_POST['tweet1']); ?>"); } </script> <form method = "POST"> <input type = "text" name = "tweet1"> <br> <input type = "submit" onclick = "postResultss()" /> </form> 的值时,没有任何内容被回显,其中$_POST['tweet1']是输入文本字段的名称,我想要显示其内容。

这里看起来有什么问题?

3 个答案:

答案 0 :(得分:2)

你做提交和onclick。那是错的。此外,不要做document.write!

这是更好的选择(js中没有php):

<?php
   if ($_SERVER['REQUEST_METHOD'] == 'POST') // check if post
      echo htmlentities($_POST['tweet1']);
?>

<form method="post">
    <input type="text" name="tweet1">
    <br>
    <input type="submit" value="Tweet!">
</form>

答案 1 :(得分:1)

而不是使用javascript来编写在您的示例中不起作用的内容,使用php生成响应以供用户查看

<form method = "POST">
    <input type = "text" name = "tweet1">
    <br>
    <input type = "submit" value='Submit' />
    <div id='msgs'>
    <?php
        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['tweet1'] ) ){
           echo $_POST['tweet1'];
        }
    ?>
    </div>
</form>

答案 2 :(得分:0)

问题是在表单提交之前调用了javascript函数(因此在php可以打印出echo之前),并且由于页面更新了document.write正在从新请求中被覆盖。

为什么不尝试这样的事情?

<form method = "POST">
    <?php echo ($_POST['tweet1']); ?>
    <input type = "text" name = "tweet1">
    <br>
    <input type = "submit"/>
</form>

或:

<script>
var text = "<?php echo ($_POST['tweet1']); ?>";
if(text != ""){
   alert(text);
}
</script>
<form method = "POST">

    <input type = "text" name = "tweet1">
    <br>
    <input type = "submit"/>
</form>