簡體   English   中英

Jquery $.post() 數據無法作為 PHP 變量檢索

[英]Jquery $.post() data cannot be retrieved as PHP variable

我很難讓 Ajax 請求 $.post() 從 Jquery 工作。 我想使用 $.post() 從表單發送數據並將其檢索為 php 變量,以便進一步將它們處理到 SQL 數據庫中。

下面,我將我的問題的簡化版本放在一頁代碼中(當 function 被觸發時,Jquery 發布到同一頁面)。 我希望使用此方法以在提交表單時不觸發頁面重新加載。

問題:我的 post() function 有效,我收到正確的警報,說明發布的數據,但是,在我提交請求后,print_r($_POST) 檢查方法保持為空。

我的問題:如何將發布的數據放入 php 變量($_POST['name'] & $_POST['email']?

<!DoCType html>
<html lang="fr-CH">

<head>
    <title> TEST </title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="/JS/jquery-3.3.1.min.js"></script>

</head>
<body>

<?php

print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
    echo "PHP received data";
} else {
 echo "It did not work";
}


?>
<div class='caseform'>
      <form id="form" method="post">
            Name:<br> <input type="text" name="name"> <br>
            Email:<br> <input type="text" name="email"> <br>
            <button id="button"> Submit </button>
</form>
 </div>

<script>
        $( document ).ready(function() {
            $("#button").click(function( event ) {
                event.preventDefault();
                var postData = $('#form').serialize();
                
                // the $.post goes to the same php file "test.php"
                var jqxhr = $.post("test.php", postData ,function() {
                }).done(function() {
                    // this works, I get an alert with postData from my form (name=&email=)
                    alert(postData);
                }).fail(function() {
                    alert("Error submitting the form.");
                })
            });
        });
</script>
</body>
</html>

問題是您沒有任何東西可以阻止后處理代碼為 GET 請求運行。 當您最初加載頁面時,它是一個 GET 請求,並且它正在運行您的print_r($_POST)當然是空的。

將該代碼包裝在這樣的檢查中,並將其移動到文件的頂部。

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    print_r($_POST); // always returns an empty array, even after clicking the submit button
    if (isset($_POST['name'])) {
        echo "PHP received data";
    } else {
     echo "It did not work";
    }
    exit();
}
?><!DoCType html>
...
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM