【问题标题】:How to call functions from PHP in javascript, Ajax not returning anything如何在javascript中从PHP调用函数,Ajax不返回任何内容
【发布时间】:2017-08-16 16:56:09
【问题描述】:

我一直在尝试将我在我的数据库(在我的 PHP 文件中)中的数据转移到我的 javascript 程序中。我正在尝试将查询结果传递给 Javascript 文件,以便我可以从这些结果中生成图表。

我曾尝试使用 ajax,但它没有任何回应。我不确定我哪里出错了。我的 PHP 文件名为 MySQLDau.php。任何帮助深表感谢!谢谢!

PHP 代码:

<?php

    header("Access-Control-Allow-Origin: *");

    //Class for holding queries
    class MySQLDao
    {
        var $dbhost = null;
        var $dbuser = null;
        var $dbpass = null;
        var $mysqli = null;
        var $dbname = null;
        var $result = null;




        //constructor
        function __construct()
        {
            $this->dbhost = Conn::$dbhost;
            $this->dbuser = Conn::$dbuser;
            $this->dbpass = Conn::$dbpass;
            $this->dbname = Conn::$dbname;
        }

        //Attempt a connection to the database
        public function openConnection()
        {
            //Try and connect to the database
            $this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
            //If the connection threw an error, report it
            if (mysqli_connect_errno())
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        //Get method for retrieving the database conection
        public function getConnection()
        {
            return $this->mysqli;
        }

        //Close the connection to the database
        public function closeConnection()
        {
            //If there is a connection to the database then close it
            if ($this->mysqli != null)
                $this->mysqli->close();
        }

        //-----------------------------------QUERY METHODS-------------------------------------

        public function generateRoomID()
        {
            $sql = "INSERT INTO room (room_id) VALUES (null);";
            $result = $this->mysqli->query($sql);
            if ($result == true)
            {
                $toReturn["status"] = true;
                $toReturn["roomID"] = $this->mysqli->insert_id;
                return $toReturn;
            }
            else
            {
                $toReturn["status"] = false;
                $toReturn["message"] = mysql_error($this->mysqli);
                return $toReturn;
            }
        }

        public function saveRoom($data)
        {
            $roomID = $data[0];
            $roomDescription = $data[1];
            $columns = $data[2];
            $rows = $data[3];

            $this->mysqli->autocommit(FALSE);

            $this->mysqli->query("UPDATE room SET room_description='".$roomDescription."' WHERE room_id='".$roomID."';");

            for ($i = 0; $i<count($columns); $i++)
            {
                for ($j = 1; $j<=$rows[$i]; $j++)
                {
                    $currentLabel = "{$columns[$i]}{$j}";
                    $this->mysqli->query("INSERT INTO shelf (shelf_label) VALUES ('".$currentLabel."');");
                    $shelfID = $this->mysqli->insert_id;
                    $this->mysqli->query("INSERT INTO room_shelf (room_id, shelf_id) VALUES ('".$roomID."','".$shelfID."');");
                }
            }

            if ($this->mysqli->commit())
            {
                $toReturn["status"] = true;
                $toReturn["message"] = "Room Created";
                return $toReturn;
            }
            else
            {
                $this->mysqli->rollback();
                $toReturn["status"] = false;
                $toReturn["message"] = "SQL Error";
                return $toReturn;
            }
        }

        public function updateShelf($data)
        {
            $shelfID = $data[0];
            $itemName = $data[1];
        }

        public function getRoomDetails($data)
        {
            $roomID = $data[0];

            $sql = "SELECT room.room_description, shelf.shelf_label, shelf.shelf_id FROM room INNER JOIN room_shelf ON room.room_id=room_shelf.room_id INNER JOIN shelf ON shelf.shelf_id=room_shelf.shelf_id WHERE room.room_id='".$roomID."';";

            $result = $this->mysqli->query($sql);

            if (mysqli_num_rows($result) > 0)
            {
                $toReturn["status"] = true;
                $toReturn["message"] = "Room Found";
                $toReturn["room_description"] = $row['room_description'];
                $shelves = [];

                foreach ($result as $row)
                {
                    $currentShelf["shelf_label"] = $row['shelf_label'];
                    $currentShelf["shelf_id"] = $row['shelf_id'];
                    array_push($shelves, $currentShelf);
                }
                $toReturn["shelves"] = $shelves;
                return $toReturn;
            }
            else
            {
                $toReturn["status"] = false;
                $toReturn["title"] = "Error";
                $toReturn["message"] = "Room Not Found";
                return $toReturn;
            }

        }

        echo "Hello World!";

        public function getResults($data){

            $sql = "SELECT * FROM room";

            $result = $this->mysqli->query($sql);

            if (mysql_num_rows($result) == 1) {
                $obj = mysql_fetch_object($result, 'obResults');

            }

            echo json_encode($obj);
        }   
    }
?>

我的 Javascript 代码的一部分:

  function callPHP() {
        $.ajax ({
            type: "GET",
            url: "MySQLDao.php",
            data: { action : 'getResults' },
            success: function(output) {
                alert(output);
            }
        });
    }

【问题讨论】:

  • 您没有展示实际编写响应的 PHP 代码的任何部分,因此我们无法为您提供帮助。确保您的 PHP 确实发送了响应。
  • 如何写回复?我找不到一个很好的例子。谢谢
  • 您需要显示您的 MySQLDao.php 文件的内容,以便我们为您提供帮助。
  • 好的,我已经添加了我的整个 php 代码。谢谢
  • 您在浏览器的网络标签中看到了什么?

标签: javascript php jquery sql ajax


【解决方案1】:

您没有任何检查 GET 参数、实例化类和调用函数的代码。您的 AJAX 请求只是创建了该类,但实际上并没有执行任何操作。

你可以做的是,在类定义的结束 } 之后是这样的:

$daoObj = new MySQLDao();
$daoObj->getResults(); // this function takes a $data parameter, but doesn't use it

这将执行您的 getResults 函数,但目前忽略了 AJAX 请求中的“data: { action : 'getResults' }”部分。让基本功能正常工作(即返回有用的东西),然后对其进行改进以根据 AJAX 请求执行不同的功能。

【讨论】:

  • 我这样做了,但 js 文件中的 ajax 出现错误。如何检查 GET 参数以及我缺少的所有其他内容?谢谢
  • 好的,在浏览器调试器的网络选项卡中,您应该能够查看 HTTP 响应,其中可能包含来自 PHP 的错误消息以进一步调试。
  • 另外,添加这个“error_reporting(E_ALL); ini_set('display_errors', 1);”到 PHP 的顶部也会有所帮助。
  • 我能找到的只是 'send @ jquery-1.7.2.min.js:4 ajax @ jquery-1.7.2.min.js:4 callPHP @ test.html:263 (匿名) @test.html:283'
  • 嗯好的。仔细查看您的代码,回显“Hello World!”需要删除。在函数之外的类中间不能有随机命令。类顶部变量前面的“var”应更改为“private”。在构造函数中,您引用了一个名为 Conn 的类,但该类既未在该文件中的任何位置定义,也未包含任何其他可能定义该类的文件。将这些更改为硬编码值以进行测试。
猜你喜欢
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
相关资源
最近更新 更多