我有一个php论坛,它将信息发送到我的数据库并将其发送回该页面,但我遇到了一个小问题。当我提交论坛时,页面完全重新加载。这是我不想要的。完成我需要论坛在后台重新加载。我已经找到了一种方法来做到这一点,但没有一个可以帮助我完成这项任务。这是下面的代码。
//this is the php file which runs the fourm
<?php
header("Location: localhost:8888");
$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();
?>
//this is the fourm
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="firstname" /></p>
<input type="submit" value="Submit" />
</form>
答案 0 :(得分:1)
尝试将Insert查询代码移动到单独的文件中。让我们说例子register.php
,它应该返回简单的文本,如成功的其他错误信息。通过这种方式,您可以轻松地检查Ajax成功回调中的数据。
$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 "success";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
如果要返回JSON,可以像下面一样更新PHP代码。
header('Content-Type: application/json');
if ($conn->query($sql) === TRUE) {
$message = "success";
} else {
$message = "Error: " . $sql . "<br>" . $conn->error;
}
$result = '{"message": ' + $message + '}';
echo json_encode($result);
在表单中添加ID以便通过DOM轻松识别
<form id="target" action="demo.php" method="post" />
<p>Input 1: <input type="text" name="firstname" /></p>
<input id="submit" type="submit" value="Submit" />
</form>
当使用$.submit
和serialize
帮助生成ajax帖子生成用户提交和JSON数据时,将触发使用$.post
。
使用包围的脚本标记
在正文结束前添加此内容 <script type="text/javascript">
$( "#target" ).submit(function( event ) {
event.preventDefault();
var jqxhr = $.post( "register.php", $(this).serialize(), function(data) {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
});
</script>