如何在不重定向到操作文件的情况下提交 PHP 表单? (使用 ajax 发送和获取数据)

How can i submit a PHP form without redirect to action file? (send and get data with ajax)

我通过在 index.php 中单击带有 $("#btn").load("form.php") 的按钮来加载表单, 我想避免在提交后将页面重定向到操作文件,并在表单下的 table 中添加一个项目。

我的演示在 http://price.parag.website

<?php include "../connection.php" ?>

<h1>Add CPU</h1>

<form method="post" action="actions/cpu_action.php">
    <label for="name">Name</label>
    <input type="text" name="cpu_name" />
    <label for="price">Price</label>
    <input type="text" name="cpu_price" />
    <input type="submit" value="Add" />
</form>
<?php

$sql = "SELECT id, cpu_name, cpu_price FROM cpu";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    echo "<table>
    <thead>
    <tr>
    <th>ID</th>
    <th>CPU NAME</th>
    <th>CPU PRICE</th>
    </tr>
    </thead>";

    while($row = $result->fetch_assoc())
    {
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['cpu_name'] . "</td>";
    echo "<td>" . $row['cpu_price'] . "</td>";
    echo "</tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
<h1>Add CPU</h1>

<form id="formupload" method="post" action="actions/cpu_action.php">
    <label for="name">Name</label>
    <input type="text" name="cpu_name" />
    <label for="price">Price</label>
    <input type="text" name="cpu_price" />
    <input type="submit" value="Add" />
</form>

现在我们必须清除表单的默认操作(我将使用 jquery)

     $('#formupload').on('submit',function(e){
             e.preventDefault();
         var formData = new FormData(this);
            $.ajax({
                type:'POST',
                url: $('#formupload').attr('action'),
                data:formData,
                cache:false,
                contentType: false,
                processData: false,
                success:function(result){
         if(condition){}
         else{}
    }
    })
   })

尝试一下它会起作用

<button type="button" onclick="loadDoc()">Request data</button>
<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("table").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "pageToPost.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("data1=bar&data2=foo");
}
</script>

这将获取响应并使用响应更新 ID 为 table 的元素,因此请确保它位于 html.