我一直试图让我的html表出现,当我点击提交按钮但它所做的只是将数据插入数据库并且html表没有出现。
这是我的index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("table.php");
});
});
</script>
</head>
<body>
<form action = "insert.php" method="post">
Firstname: <input type="text" name="firstname"></br>
Lastname: <input type="text" name="lastname"></br>
Middlename: <input type="text" name="middlename"></br>
<button type="submit">submit</button>
</form>
<div id="div1">
</div>
</body>
</html>
这是我的table.php
<?php
$con = mysqli_connect("localhost","root","","study");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to mysql" . mysqli_connect_error();
}
echo '<table border = 1>';
echo '<tr>';
echo ' <th>FIRSTNAME</th>';
echo '<th>LASTNAME</th>';
echo ' <th>MIDDLENAME</th>';
echo ' <th>DELETE</th>';
echo ' </tr>';
$result = mysqli_query($con,"SELECT * FROM sample_employers");
while($row=mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['middlename'] . "</td>";
echo "<td> <input type='button' value='Delete' </td>";
echo "</tr>";
}
mysqli_close($con);
echo '</table>';
?>
我在index.php中做了一些编辑。我把提交按钮放在form标签之外,然后出现了html表,但现在的问题是没有数据插入到数据库中。所以我将如何使html表出现并同时将数据插入到数据库中我点击提交按钮。??
答案 0 :(得分:0)
// example 1 GET
$(document).ready(function(){
$("#submitButt").click(function(e){ // u should give a id to the button.
e.preventDefault(); // this is to prevent the form submit by it self
// using ajax to submit
$("#div1").load("insert.php",
$(this.form).serialize(); // this will use GET to submit data
);
});
});
// example 2 POST
$(document).ready(function(){
$("#submitButt").click(function(e){ // u should give a id to the button.
e.preventDefault(); // this is to prevent the form submit by it self
// using ajax to submit
$("#div1").load("insert.php",
$(this.form).serializeArray(); // this will use POST to submit data
);
});
});
http://jsfiddle.net/9kcek/
单击提交按钮时,使用篡改数据检查请求。
答案 1 :(得分:0)
如果按提交,则系统会将您重定向到insert.php
。因此,您的点击事件将永远不会被执行。您必须先阻止重定向才能加载数据。
此外,您需要切换数据发布的方式。由于您希望直接在当前页面上插入表格,因此应切换到ajax方法。您的数据将通过insert.php
在后台发送到$.ajax
,然后您可以#div1
将内容table.php
加载到<script>
$(document).ready(function () {
var $form = $('form');
$form.submit(function (event) {
event.preventDefault();
var formData = $form.serialize(),
url = $form.attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function () {
$("#div1").load("table.php");
}
});
});
});
</script>
。
{{1}}