【问题标题】:PHP not getting $_POST from ajax postPHP 没有从 ajax 帖子中获取 $_POST
【发布时间】:2015-01-05 17:03:00
【问题描述】:

我正在尝试将数据发布到同一页面。

我可以看到来自 ajax 的帖子工作正常,但我的index.php 中的$_POST 在提交表单后没有找到帖子。

<form method="post" id="classic_login" action="">
    <input type="text" name="user" placeholder="Username" class="classic_field" id="user_field" />
    <input type="text" name="pass" placeholder="Password"  class="classic_field" id="pass_field" />
    <input type="submit" name="login" value="Login" class="classic_button" id="login_button" />
    <input type="submit" name="register" value="Register" class="classic_button" id="register_button" />
</form> 

我试过print_r($_POST)isset在提交后都不会改变

print_r($_POST);
if(isset($_POST['user']) && isset($_POST['pass']))
   echo "works";

在测试提交后打印表单数据我得到:user=testuser&pass=testpass

$("#classic_login").submit(function(event) {
    var formdata    =   $(this).serialize();
    event.preventDefault();

    $.ajax
    ({
        url: "",
        type: 'POST',
        data: formdata,
        //success: function(response) { alert(response); },
        error:  function() { alert("fail"); }
    });

});  

【问题讨论】:

  • 你为什么评论你的成功方法?
  • 就我的理解而言,如果你想将表单发布到同一个php文件中,你可以简单地使用action="your.php"。那你为什么要用ajax呢?
  • @Abdul 没有理由,只是在测试。忘记取消注释。

标签: php jquery html ajax forms


【解决方案1】:

或者,您可以使用document.URL 在同一页面上发出请求。然后在 PHP 中,在请求之后包含一个exit;

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo '<pre>';
    print_r($_POST);
    exit; // this is important!
}

?>

<form method="post" id="classic_login" action="">
    <input type="text" name="user" placeholder="Username" class="classic_field" id="user_field" />
    <input type="text" name="pass" placeholder="Password"  class="classic_field" id="pass_field" />
    <input type="submit" name="login" value="Login" class="classic_button" id="login_button" />
    <input type="submit" name="register" value="Register" class="classic_button" id="register_button" />
</form> 

<!-- this is no brainer, of course you need to load the library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("#classic_login").submit(function(event) {
    var formdata  = $(this).serialize();
    event.preventDefault();

    $.ajax({
        url: document.URL, // you can use this
        type: 'POST',
        data: formdata,
        success: function(response) { 
            alert(response); 
        }
    });
});
</script>

Sample Output

【讨论】:

  • 忘了说,js是外部的,它的索引路径是:js/main.js
  • @joe 当然,这个答案很简单,不需要大的修改,请试试这个
  • 好的,试过了,还是没有,print_r 永远不会执行或从“Array()”改变
  • @joe 除了已经有一个工作演示之外,我不知道能提供更多帮助。它已经在同一页面上。实际上,您可以直接复制此答案。这是演示codepad.viper-7.com/h2UY4u
  • 我在收到警报时的反应与您的非常不同,我正在将整个 html 打印在警报中:i.imgur.com/J5GMQLC.png 这与它有什么关系吗?就像我说我的 JS 是外部的,而不是 index.php
猜你喜欢
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
相关资源
最近更新 更多