PHP没有从ajax帖子获得$ _POST

时间:2014-11-09 07:35:56

标签: php jquery html ajax forms

我试图将数据发布到同一页面。

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

<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";

在测试提交后打印formdata我得到:user = testuser&amp; 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"); }
    });

});  

1 个答案:

答案 0 :(得分: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