簡體   English   中英

ajax提交表單為什么它不能回顯$ _POST

[英]ajax submit form why it cannot echo $_POST

我正在使用ajax提交表單進行測試(提交給我自己的頁面“new1.php”)

我想要的是,點擊提交按鈕后,它將回顯名字和姓氏。 但我不知道為什么我提交后看不到名字和姓氏。

這是new1.php頁面

<?php 
echo $_POST['firstname']."<br>";
echo $_POST['lastname']."<br>"; 
 ?>  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>
<body>
    <form id="myform" action="new1.php" method="post">
        Firstname : <input type="text" name="firstname"> <br>
        Lastname : <input type="text" name="lastname"> <br>
        <input type="submit" value="Submit">
    </form>

        <script>
        // this is the id of the form
$("#myform").submit(function(e) {

    $.ajax({
           type: "POST",
           url: 'new1.php',
           data: $("#myform").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert('yeah'); // show response from the php script.
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});
    </script>
</body>
</html>

在您的情況下,最好的選擇是在PHP代碼中使用json_encode檢索值為JSON格式,然后通過數據對象訪問這些值。

例:

PHP代碼:

if($_POST)
{
    $result['firstname'] = $_POST['firstname'];
    $result['lastname'] = $_POST['lastname'];

    echo json_encode($result);
    die(); // Use die here to stop processing the code further 
}

JS代碼:

$("#myform").submit(function (e) {

    $.ajax({
        type : "POST",
        url : 'new1.php',
        dataType : 'json', // Notice json here
        data : $("#myform").serialize(), // serializes the form's elements.
        success : function (data) {
            alert('yeah'); // show response from the php script.
            // make changed here
            $('input[name="firstname"]').text(data.firstname);
            $('input[name="lastname"]').text(data.lastname);
        }
    });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

當您使用表單作為序列化時,您必須像這樣檢索。

像這樣編輯你的ajax:

data: { formData: $("#myform").serialize()},

然后你可以在你的控制器中檢索這樣的:

parse_str($_POST['formData'], $var);
echo "<pre>";
print_r($var);
exit;

改變

alert('yeah'); // show response from the php script.

alert(data); // show response from the php script.

在這里對javascript進行一些更改:

success: function(data)
       {
           $('#response').html(data); // show response from the php script.
       }

並在HTML代碼中創建一個id response的div

<div id="response"></div>

由於您通過ajax調用new1.php並且數據(名字,姓氏和頁面代碼)返回到java腳本變量(數據),您需要將數據注入到文檔中,因此不會顯示值firstname,lastname

嘗試這個

$.ajax({
    type: "POST",
    url: 'new1.php',
    data: $("#myform").serialize(), // serializes the form's elements.
    success: function(data) {
        document.documentElement.innerHTML = data;
    }
});

暫無
暫無

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

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