php - AJAX 不会阻止重定向到 PHP 页面
问题描述
在 AJAX 的帮助下,我一直在尝试防止在提交表单后自动重定向到空白 PHP 页面,但我没有管理。提交到表单的数据正在输入到 MySQL 表中,但是单击提交后,我总是被重定向到空白insert.php
页面。这是 HTML 表单:
<tr>
<td></td>
<form class = "ajax" action = "insert.php" method="POST">
<td><input type="text" class = "inputs" name = "dcs" id = "dcs"/></td>
<td><input type="text" class = "inputs" name = "qty" id = "qty"/></td>
<td><input type="text" class = "inputs" name = "rate" id = "avg"/></td><td></td>
<td><div style = "position: relative;"><input type="submit" onclick="add_new_entry();" id = "submit"/></div></td>
</form>
<td></td>
<tr>
这是jQuery函数:
$(document).ready(function() {
$('form.ajax').submit(function(event) {
event.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success = function(response) {
alert(response);
}
});
return false;
});
});
这里是insert.php
:
<?php
include "db_connect.php";
$code = 4;
$dcs = mysqli_real_escape_string($conn, $_POST['dcs']);
$qty = mysqli_real_escape_string($conn, $_POST['qty']);
$rate = mysqli_real_escape_string($conn, $_POST['rate']);
$total = $qty * $rate;
$sql = "INSERT INTO entries VALUES ('$code',
'$dcs','$qty','$rate','$total');";
// $conn is the connection
mysqli_query($conn, $sql)
mysqli_close($conn);
?>
请让我知道我应该做的更改,以便在提交表单后我不会重定向到 PHP 页面。
让我知道是否应该提供任何其他代码片段。
非常感谢。
解决方案
所以有一个巧妙的技巧,您可以添加return false;
onclick 功能以防止页面提交。我认为这里的问题是你在阻止它提交之前已经提交了表单,否则你可以做的是在提交部分之前创建一个点击事件,这需要阻止表单的提交或者使用 jquery $.post en 而不是提交事件
推荐阅读
- android - 从 LiveData 触发第二个查询并合并结果(Firestore)?
- android - Firebase toObject 与 ref
- node.js - node.js 和 AWS Lambda 函数在回调后继续执行函数
- apache-nifi - 在 NiFi 中压缩具有匹配模式的多个文件
- python - Python Selenium 奇怪的 ElementNotVisible 异常
- c - 在 C 程序中调用 strace(+Seg 错误)
- swift - RxSwift:除了使用回调之外,如何建立可观察的函数调用链?
- scala - 如何在 Spark 中创建 Schema 文件
- .htaccess - .htaccess - 删除一个变量和 301 重定向,但不影响其他变量?
- python - Numpy:关于 numpy.ufunc.reduceat 的第二条规则?