我很想知道是否可以像窗口一样进行div重新加载。这样做的原因是我有一个论坛,但我不希望在四个完成后重新加载整页。所以我想知道是否只有div或论坛部分中的元素可以执行后台重新加载,或者只是在按下提交按钮时由他们自己加载。
这是在一个名为forum的文件中,其中输入了信息。我希望它不会重新加载页面,而是保留在该论坛上并仍然将数据发送到数据库。
<html>
<body>
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="firstname" /></p>
<input type="submit" value="Submit" />
</form>
<div id = "load_results"></div>
</body>
</html>
这是将信息发送到数据库,但我希望它能够谨慎地完成。
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['firstname'];
$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
答案 0 :(得分:0)
是的,有办法。它被称为AJAX - 但是,不用担心,它非常简单。
您的代码将如下所示:
<强> HTML:强>
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="firstname" /></p>
<input type="submit" value="Submit" />
</form>
<强> JS / jQuery的:强>
$(function(){
$('form').submit(function(evt){
//next line stops form submission from sending you to `demo.php`
evt.preventDefault(); //evt stands for "event" - can be anything. I use e.preventDefault()
var fn = $('[name=firstname]').val();
$.ajax({
type: 'post',
url: 'demo.php', //send data ONLY to demo.php -- page stays as it is
data: 'first='+fn,
success: function(d){
if (d.length) alert(d);
}
}); //END ajax
}); //END document.ready
<强> demo.php 强>
<?php
$fn = $_POST['fn'];
//Do your database insert here
//If you wish, you can return some data to the AJAX's success function:
echo 'You submitted: ' .$fn;
以下是一些简单的AJAX示例帖子: