提交弹出表单后使用 AJAX 更改页面内容

Change page contents with AJAX after submiting a popup form

我遇到这个问题,为了更改页面内容,我必须接收用户输入。我想通过弹出表单来做到这一点。单击弹出窗口上的按钮 "submit" 后,我想将表单输入发送到 php 文件,在该文件中我连接到数据库并通过 JSON 将检索到的信息发送到 js 文件,我在其中使用 $.post() 方法来实现所有这些。问题是页面内容在没有重新加载的情况下被更改,我被重定向到页面 http://localhost/statistics.php?major=KN&year=2011 但我想留在页面 http://localhost/statistics.php 上。这就是为什么我首先使用 AJAX 的原因。 major=KN & year=2011 是我的 POST 参数。提交弹出表单后是否可以更改页面内容?任何帮助将不胜感激。

这是我认为可能与解决问题相关的代码:

    <html>
        <head>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <script src="ch/Chart.js"></script>
            <script src="js/statistics_js.js"></script>
        </head>
        <body>
        <div id="content">
            <div id="abc">
                <div id="popupContact">
                    <form id="form1" name="form1">
                        <img class="close" src="images/3.png" onclick ="div_hide_group_popup()">
                        <h2>Fill the form</h2>
                        <hr>
                        <input name="major" placeholder="Major" type="text">
                        <input name="year" placeholder="Year" type="number">
                        <button id="submit1">Submit</button>
                    </form>
                </div>
            </div>
            <div id="page">
                <canvas id="myChart"></canvas>
            </div>
            <aside>
                <h3>Compare</h3>
                <ul>
                    <li id="group"><a href="#">groups</a></li>
                </ul>
            </aside>
        </div>
        </body>
    </html>

js/statistics_js.js 文件:

    function error(){
        alert('Error!');
    }

    $(document).ready(function(){
        $('#group').on('click', function(e) {
            e.preventDefault();
            document.getElementById('abc').style.display = "block";
        });
    });

    $(document).ready(function(){
        $("#submit1").click( function() {
            $.post( "http://localhost/group_sort.php", $("#form1").serialize(), "JSON").done(function(data) {
                    //This should use the Chart.js library to draw a chart on the canvas with the data retrieved from the server.
                    var barChartData = {
                        labels : data.groups,
                        datasets : [
                            {
                                fillColor : "rgba(151,187,205,0.5)",
                                strokeColor : "rgba(151,187,205,0.8)",
                                highlightFill : "rgba(151,187,205,0.75)",
                                highlightStroke : "rgba(151,187,205,1)",
                                data : data.groups_total_points
                            }
                        ]
                    }
                    var ctx = document.getElementById("myChart").getContext("2d");
                    window.myBar = new Chart(ctx).Bar(barChartData, {
                        responsive : true
                    });
                }).error(error);
        });
    });

    function div_hide_group_popup(){
        document.getElementById('abc').style.display = "none";
    }

我的group_sort.php:

    <?php
        require "config.php";
        try {
            $conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
        }
        catch(PDOException $e) {
            die("Database connection could not be established.");
        }
        $conn->exec("SET NAMES UTF8");
        $major = $_POST['major'];
        $year = $_POST['year'];
        $sql = "SELECT result.group, SUM(result.grade) AS group_total_points
                FROM (
                    SELECT *
                    FROM students AS s
                    INNER JOIN points AS p
                    ON s.fn = p.student_fn
                ) result
                WHERE result.major = '$major' AND result.year = '$year'
                GROUP BY result.group
                ORDER BY group_total_points DESC";
        $query = $conn->query($sql);
        if($query->rowCount() > 0) {
            $data = array (
                "groups" => [],
                "groups_total_points" => [],
                );
            while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
                $data["groups"][] = $row["group"];
                $data["groups_total_points"][] = $row["group_total_points"];
            }
            echo json_encode($data);
        }
        else {
            echo mysql_error();
        }

        $conn = null;
    ?> 

您的提交按钮在您单击时可能正在提交表单。阻止点击时的默认操作:

    $("#submit1").click( function(event) {
        event.preventDefault();
        $.post( "http://localhost/group_sort.php", $("#form1").serialize(), "JSON").done(function(data) {

您的问题是您的提交按钮正在完成提交。我建议将其更改为普通按钮以防止提交,尽管他们可以按回车键并提交表单。为此,您必须阻止表单的提交功能。

更简单的解决方案是用简单的 div:

替换表格
<div class="form">
   <img class="close" src="images/3.png" onclick ="div_hide_group_popup()">
   <h2>Fill the form</h2>
   <hr>
   <input class="submit-form" name="major" placeholder="Major" type="text">
   <input class="submit-form" name="year" placeholder="Year" type="number">
   <button id="submit1">Submit</button>
</div>

然后使用 jquery 您可以 select document.ready 回调中的表单元素:

 $(document).ready(function(){
    var input = $('input.submit-form');
    $("#submit1").click( function() {
        $.post( 
             "http://localhost/group_sort.php", 
             input.serialize(), 
             "JSON").done(function(data) { //...