如何在不重定向到操作文件的情况下提交 PHP 表单?

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


我的演示在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";

}


开满天机
浏览 116回答 2
2回答

jeck猫

<h1>Add CPU</h1><form id="formupload" method="post" action="actions/cpu_action.php">&nbsp; &nbsp; <label for="name">Name</label>&nbsp; &nbsp; <input type="text" name="cpu_name" />&nbsp; &nbsp; <label for="price">Price</label>&nbsp; &nbsp; <input type="text" name="cpu_price" />&nbsp; &nbsp; <input type="submit" value="Add" /></form>现在我们必须清除表单的默认操作(我将使用 jquery)&nbsp; &nbsp; &nbsp;$('#formupload').on('submit',function(e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var formData = new FormData(this);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type:'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: $('#formupload').attr('action'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data:formData,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cache:false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contentType: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; processData: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success:function(result){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(condition){}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else{}&nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp;})试试这个它会工作

一只名叫tom的猫

<button type="button" onclick="loadDoc()">Request data</button><script>function loadDoc() {&nbsp; var xhttp = new XMLHttpRequest();&nbsp; xhttp.onreadystatechange = function() {&nbsp; &nbsp; if (this.readyState == 4 && this.status == 200) {&nbsp; &nbsp; &nbsp; document.getElementById("table").innerHTML = this.responseText;&nbsp; &nbsp; }&nbsp; };&nbsp; xhttp.open("POST", "pageToPost.php", true);&nbsp; xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");&nbsp; xhttp.send("data1=bar&data2=foo");}</script>这将获取响应并使用响应更新带有 id 的元素table,因此请确保它在 html 中。
打开App,查看更多内容
随时随地看视频慕课网APP