首页 > 解决方案 > 用户单击通知时执行 PHP PDO 查询后,XMLHttpRequest 未重定向到 URL

问题描述

我遇到了一个问题,即 XMLHttpRequest 没有将用户重定向到我在用户单击通知时设置的 URL。当我使用 MySQLi 时,XMLHttpRequest 工作正常。但是,我需要使用 PHP PDO 而不是 MySQLi,所以我尝试将 MySQLi 代码转换为 PHP PDO。当我使用 PDO 代码时,数据库已更新,但用户未定向到 URL。再加上一个警报出来了,但只说成功,如下所示。

在此处输入图像描述

这是 XMLHttpRequest 的代码。

<?php
    $sql = "SELECT COUNT(*) AS notificationCount FROM appointment
                    LEFT JOIN users AS lecturer ON appointment.lecturer_id = lecturer.username
                    LEFT JOIN course AS course ON appointment.course = course.course_id
                    WHERE appointment.lecturer_id = :user AND appointment_status='Pending';
                    ";

            $notificationURL = '../lecturer/lecturer-view-pending-appointment.php';

            $stmt = $db->prepare($sql);
            $stmt->execute(array('user' => $user));

            $row = $stmt->fetch();

            $notificationCount = $row [ 'notificationCount' ];

            echo 
            "
                <script type='text/javascript'>
                function HandleNotificationsLecturer()
                {
                    // AJAX codes
                    var xmlhttp

                    if ( window.XMLHttpRequest )
                        xmlhttp = new XMLHttpRequest()
                    else
                    {
                        // code for IE6, IE5
                        xmlhttp = new ActiveXObject ( 'Microsoft.XMLHTTP' )
                    }

                    xmlhttp.onreadystatechange = function()
                    {
                        if ( this.readyState == 4 && this.status == 200 )
                        {
                            if ( xmlhttp.responseText === 'Success' )
                            {
                                location.href = '$notificationURL'
                            }
                            else
                                alert ( xmlhttp.responseText )
                        }
                    }

                    xmlhttp.open ( 'POST', '../ajax/ajax-remove-notification-lecturer.php', true )
                    xmlhttp.setRequestHeader ( 'Content-type', 'application/x-www-form-urlencoded' )
                    xmlhttp.send ( 'lecturer_id=$user' )
                }
                </script>
            ";
?>

这是使用 MySQLi 时的代码:

<?php
        $lecturer_id = $_POST['lecturer_id'];
        require_once ( '../database.php' );
        $connection = OpenDatabase();
        QueryDatabase ( $connection, "UPDATE appointment SET appointment_status='Notified' WHERE lecturer_id='$lecturer_id' AND appointment_status='Pending'" );
        CloseDatabase ( $connection );
        die ( 'Success' );
?>

这是 PHP PDO 的代码:

<?php
require ("../global-include.php");

    if (isset($_POST['lecturer_id']))
    {
        $remove_notification_query = "UPDATE appointment SET appointment_status='Notified' WHERE lecturer_id=:lecturer_id AND appointment_status='Pending'";
        $remove_statement= $db->prepare($remove_notification_query);
        $remove_statement->bindParam(':lecturer_id', $_POST['lecturer_id']);
        $remove_statement->execute();
        die ( 'Success' );
    }
?>

MySQLi 和 PDO 的数据库连接也不同。这是 MySQLi 的数据库连接:

<?php
    function OpenDatabase()
    {
        $dbhost = 'localhost';
        $dbuser = 'root';
        $dbpassword = '';
        $database = 'stulec';

        // open a connection to the database server
        $connection = new mysqli ( $dbhost, $dbuser, $dbpassword, $database );

        if ( $connection->connect_errno )
        {
            die ( 'Connect failed: ' . $connection->connect_error );
        }

        return $connection;
    }

    function QueryDatabase ( $connection, $query )
    {
        $query = str_replace ( '"', '`', $query );

        $result = $connection->query ( $query );

        if ( !$result )
        {
            die ( 'Error in query: ' . $connection->error );
        }

        return $result;
    }

    function GetNumRows ( $result )
    {
        return $result->num_rows;
    }

    function ReadField ( $result, $row, $field )
    {
        $result->data_seek ( $row );
        $row = $result->fetch_assoc();

        return $row [ $field ];
    }

    function GetLastInsertedID ( $connection )
    {
        return $connection->insert_id;
    }

    function CloseDatabase ( $connection )
    {
        $connection->close();
    }
?>

这是 PDO 的数据库连接:

<?php
    class PDOConnection 
    {
        private static $dbConnection = null; //static variables - doesn't change, when update, update for everyone

        /** 
         *Return DB connection or create initial connection
        *@return object (PDO connection)
        *@access public
        */

        public static function getConnection()
        {
            //create connection
            if (!self::$dbConnection) 
            {
                try
                {
                        self::$dbConnection = new PDO ('mysql:host=localhost; dbname=stulec','root','');
                        self::$dbConnection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                }

                catch(PDOException $e) 
                {
                    echo $e->getMessage();
                }
            }

            return self::$dbConnection; //return the connection
        }
    } //end of class
?>

我已经检查并检查了我的网络响应,但也没有任何结果。

标签: phpxmlhttprequest

解决方案


更新:

我终于在朋友的帮助下得到了答案。他告诉我这是因为 die('Success'); die('Success') 有不必要的空格。所以他建议使用

if ( xmlhttp.responseText.indexOf('Success') >= 0)

代替

if ( xmlhttp.responseText == 'Success' )

indexof 将检查字符串是否包含单词 Success 而不管其他任何内容。

感谢那个朋友和其他正在考虑如何帮助我的人。


推荐阅读