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 页面。

如果我应该提供任何其他代码片段,请告诉我。

非常感谢。

Star595198770 回答:AJAX 不会阻止重定向到 PHP 页面

所以有一个巧妙的技巧,您可以在 onclick 函数上添加 return false; 以防止页面提交。我认为这里的问题是你在阻止提交之前已经提交了表单,否则你可以做的是在提交部分之前创建一个点击事件,这需要阻止提交表单或使用 jquery $.post en 而不是提交事件

本文链接:https://www.f2er.com/4557.html

大家都在问