繁体   English   中英

使用JavaScript调用php函数时,php $ _POST返回空

[英]Php $_POST returns empty when using javascript to call php function

我还在学习php和java脚本。 我正在创建一个简单的联系表单,并使用$ _Server [php_self]将表单操作设置为同一页面

我要做的是,当有人提交给我的表单时,它将显示一条消息,其中包括在同一页面上提交的名称。 用消息替换联系表。

我也尝试将动作指向另一个PHP页面。 而且仍然没有用。 Javascript可以那样工作吗? 或者我必须使用不同的代码或语言来做到这一点。

这是我的代码

 <!DOCTYPE html> <html> <head> <?php include 'action.php'; ?> <title> My profle</title> <meta name="robots" content="noindex"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="contact"> <form class="form" class="contact" id="contact-form" action="action.php" method="POST"> Name: <br> <input type="text" class="field" name="name"><br> Number:<br> <input type="text" class="field" name="number"><br> Email:<br> <input type="email" class="field" name="email:>"<br> <br> <input type="submit" class="submit" name="submit" value="submit" onclick ="document.getElementById('contact-form').innerHTML='<?php thankyou();?>'"> </form> </div> </body> </html> 

然后这是action.php

 <?php function thankyou(){ $name = $_POST['name']; echo "Thank you"." $name ! Your message has been submitted."; } ?> 

您在这里有几个不同的问题。

首先是对PHP和JS的运行时间缺乏了解。

第二个是在加载新页面时DOM更改丢失。

这是正在发生的事情:

  1. 浏览器请求页面
  2. PHP运行( $_POST没有name键)
  3. 浏览器获取页面
  4. 您单击提交按钮
  5. JavaScript运行,并设置了innerHTML (请记住,PHP在步骤2中返回了)
  6. 表单提交导致浏览器导航到新页面
  7. PHP再次运行
  8. 浏览器将获取新页面……而对上一页所做的DOM更改将丢失

进一步阅读: 客户端编程和服务器端编程有什么区别?

我很乐意在评论中听到更好的方法来做到这一点,因为这已经超出了我的头脑,而且我知道有更好的解决方案……但是,在您遇到的情况下,我将做以下事情:

<!DOCTYPE html>
<html>
<head>
    <title> My profle</title>
    <meta name="robots" content="noindex">
    <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>
<div class="contact">
   <form class="form" class="contact" id="contact-form" action="" method="POST">
           <?php 
               if(isset($_POST)){
                   //process data however (I'm assuming) you need to - even if just posting to another script at this point...
                   echo 'Thank you '.$_POST['name'].' ! Your message has been submitted';
               }
               else{
                    echo 'Name: <br>
                    <input type="text" class="field" name="name"><br>
                    Number:<br>
                    <input type="text" class="field" name="number"><br>
                    Email:<br>
                    <input type="email" class="field" name="email"><br>
                    <br>
                    <input type="submit" class="submit" name="submit" value="submit">';
               }
           ?>
       </form>
</div>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM