首页 > 解决方案 > 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 页面。

让我知道是否应该提供任何其他代码片段。

非常感谢。

标签: phphtmljqueryajax

解决方案


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


推荐阅读