如何从jquery.POST访问$_POST变量


How do I access $_POST variables from a jquery .post?

我正在尝试使用jquery-post将表单数据异步发送到php文件,该文件将把数据上传到我的数据库。

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <div id="contact_form">  
    <form id="contact" name="contact" method="post">  
  <fieldset>  
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="name" size="30" value="" class="text-input" />  
    <label for="email" id="email_label">Return Email</label>  
    <input type="text" name="email" id="email" size="30" value="" class="text-input" />  
    <label for="phone" id="phone_label">Return Phone</label>  
    <input type="text" name="phone" id="phone" size="30" value="" class="text-input" />  
    <br />  
    <input type="submit" name="submit" class="button" id="submit_btn" value="Submit" />  
  </fieldset>  
</form>  
</div>  
  <div id="result"></div>
<script>
$(document).ready(function(){
/* attach a submit handler to the form */
$("#submit_btn").submit(function(event) {
  /* stop form from submitting normally */
  event.preventDefault();
 $.post("process.php", $("#contact").serialize());

  return false;
});
});
</script>
</body>
</html> 

我知道它是对数据进行串行编码的,但我的php脚本没有接收到它,我不确定我做错了什么。我知道这很简单,但我已经为此工作了几天,似乎无法理解。我知道如何在没有jquery的情况下做到这一点,但在这种情况下我真的需要它。这是我的php:

if(isset($_POST['submit']))
{
    $var_name = $_POST['name'];
    $var_email = $_POST['email'];
    $var_phone = $_POST['phone'];
//This establishes a connection to the database. It also says what to do if the connection fails.
try {
    $db_handle = new PDO("mysql:host=$server;dbname=$database", $db_username, $db_password);
    $db_handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $db_handle->prepare('INSERT INTO contact(name, email, phone) VALUES(:name, :email, :phone)');   
    $stmt->execute(array(
        ':name' => $var_name,
        ':email' => $var_email,
        ':phone' => $var_phone,
        ));
    } catch(PDOException $e) {
    echo 'Error: ' . $e->getMessage();
    }
}
$("contact").serialize()

应为:

$("#contact").serialize()

您的选择器不正确,因此您实际上没有向服务器发送任何内容。下次,请在浏览器工具中检查请求。

当您使用jQuery序列化表单时,提交按钮不包括在内,因此您应该替换

if(isset($_POST['submit']))

通过

if ($_SERVER['REQUEST_METHOD'] === 'POST')

编辑

通过$("#contact").submit(...); 更改$("#submit_btn").submit(...);

http://api.jquery.com/serialize/

jquery API声明提交按钮值将不会被传递。因此,这篇文章可能会很好地访问您的php请求。建议您查找一个必填字段,而不是在条件中查找$_post["submit"]。

您也可以尝试在编写代码之前使用var_dump($_POST),并查看脚本的效果。