【问题标题】:Change page contents with AJAX after submiting a popup form提交弹出表单后使用 AJAX 更改页面内容
【发布时间】:2015-02-05 17:35:59
【问题描述】:

我有这个问题,为了更改页面内容,我必须接收用户输入。我想通过弹出表单来做到这一点。单击弹出窗口上的“提交”按钮后,我想将表单输入发送到php 文件,在该文件中我连接到数据库并通过 JSON 将检索到的信息发送到我使用$.post() 方法的js 文件实现这一切。问题是页面内容在没有重新加载的情况下被更改,我被重定向到页面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;
    ?> 

【问题讨论】:

    标签: javascript php jquery ajax popup


    【解决方案1】:

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

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

    【讨论】:

    • 这就是它应该做的 - 将输入从表单发送到 php 文件。现在我按照你说的做了,虽然我从error() 函数中得到了一个警告“错误”。知道如何查看它的来源吗?
    • 不,您想通过 Ajax 获取输入,而不是提交表单。可能发生的情况是您的表单正在提交,页面正在刷新,并且您的 Ajax 调用从未被执行。当您阻止默认设置时,您的 Ajax 代码正在被使用并出现错误。错误信息是什么?
    • 这只是“错误!”因为这就是我的 error() 方法的主体。知道如何更改它以便我得到实际的错误吗?
    • 错误是"NetworkError: 404 Not Found - http://localhost/group_sort.php",但我有一个这样命名的文件...
    • 该文件不在应有的位置。否则你是对的event.preventDefault();
    【解决方案2】:

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

    更简单的解决方案是用简单的 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 你可以在 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) { //...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 2014-03-09
      • 2013-02-09
      • 2011-10-24
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多