【问题标题】:AJAX not producing correct outputAJAX 没有产生正确的输出
【发布时间】:2017-08-23 14:21:22
【问题描述】:

所以我试图从 javascript 调用一个 php 方法,这样我就可以查询数据库并将结果放入我的 js 功能中。目前,我的 ajax 中的 console.log(output) 正在输出:

字符串 '{"action":"getResults"}' (length=23)

不太确定为什么要这样做,它应该返回的查询结果只是数据库中的一个条目。

我的 Javascript 文件的一部分:

function callPHP() {
  $.ajax({

    type: "GET",
    datatype: "application/json",
    url: "BaseClass.php",
    data: {
      action: 'getResults'
    },
    //error: function(err){console.log(err)},
    success: function(output) {

      console.log(output);
      //alert(output);
    }
    //error, function(err){console.log(err)}
  });
}

callPHP();

BaseClass.php:

<?php

error_reporting(E_ALL); ini_set('display_errors', 1);

require("Conn.php");
require("MySQLDao.php");

$param=$_REQUEST['action'];

//echo json_encode($_GET);


echo var_dump(json_encode($_GET));

/*
$handle = fopen("php://input", "rb");
$param = '';
while (!feof($handle)) {
    $param .= fread($handle, 8192);
}
fclose($handle);
*/

if (empty($param))
{
    $returnValue["status"] = false;
    $returnValue["title"] = "Error";
    $returnValue["message"] = "No Data Recieved paige" .$param ."...";
    echo json_encode($returnValue);
    return;
}
else
{
    $dao = new MySQLDao();
    if ($dao->openConnection() == false)
    {
        $returnValue["status"] = false;
        $returnValue["title"] = "Error";
        $returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
        echo json_encode($returnValue);
    }
    else
    {
        //Decodes data, dont change
        $body = json_decode($param, true);
        $recieved = $body["data"];

        //Gets the result of a query
        //$result = $dao->MySQLDaoMethodName(parameters);

        //Return the result of the query
        //echo json_encode($result);
    }
    $dao->closeConnection();
    return;
}
?>

Conn.php - 这是所有的连接信息,*出于保密原因:

<?php

    error_reporting(E_ALL); ini_set('display_errors', 1);

    class Conn
    {
        public static $dbhost = "***";
        public static $dbname = "***";
        public static $dbuser = "***";
        public static $dbpass = "***";
    }
?>

MySQLDao.php - 这个文件包含查询:

   <?php

    error_reporting(E_ALL); ini_set('display_errors', 1);

    //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 getResults($data)
        {



            $sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";

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


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

            //}

            //echo json_encode($result);

            echo($result);

            //return "yay";

        }

    }
?>

如何解决这个问题,只需将查询结果打印到网页上?我多年来一直坚持这一点。欢迎和赞赏任何帮助。提前致谢。

【问题讨论】:

  • 您可能想要重命名问题。这不是关于调用 PHP 函数 - 它是关于 AJAX 调用产生的输出不是您所期望的。
  • 好吧,你从来没有真正从你的最后一个else 块中回显出来。因此,如果$param 不为空,并且$dao-&gt;openConnection() 为真,则不会发回任何内容。
  • //if (mysql_num_rows($result) == 1) { // $obj = mysql_fetch_object($result, 'obResults'); - 我想知道您是否正在尝试使用那些不与 mysqli_ api 混合的 mysql_ 函数。
  • 这与您在此处的查询有何不同? stackoverflow.com/questions/45722685/…

标签: javascript php mysql ajax


【解决方案1】:

您的 BaseClass 仅在出现错误时才输出,因为您从不使用 echo

if (empty($param))
{
    $returnValue["status"] = false;
    $returnValue["title"] = "Error";
    $returnValue["message"] = "No Data Recieved paige" .$param ."...";
    echo json_encode($returnValue);//Only output
    return;
}
else
{
    $dao = new MySQLDao();
    if ($dao->openConnection() == false)
    {
        $returnValue["status"] = false;
        $returnValue["title"] = "Error";
        $returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
        echo json_encode($returnValue);//Only output
    }
    else
    {
        //Decodes data, dont change
        $body = json_decode($param, true);
        $recieved = $body["data"];

        //Gets the result of a query
        //$result = $dao->MySQLDaoMethodName(parameters);

        //Return the result of the query
        //echo json_encode($result);
        //All of these are commented out
        echo json_encode($result);//Fix
    }
    $dao->closeConnection();
    return;
}

【讨论】:

  • 我已经取消注释这些,所以现在是 //Decodes data, dont change $body = json_decode($param, true); $recieved = $body["data"]; //获取查询结果 $result = $dao->getResults($recieved); //返回查询结果 echo json_encode("the result" .$result);但是它仍然没有产生我想要的
  • 更改后的输出是什么?
  • 字符串 '{"action":"getResults"}' (length=23) {"current_field":null,"field_count":null,"lengths":null,"num_rows":null, "type":null}"结果"
【解决方案2】:

不太清楚为什么会这样

这样做是因为:

echo var_dump(json_encode($_GET));

您获取解析查询字符串的结果,将其转换为 JSON 字符串,然后将该字符串传递给 var_dump(它告诉您它是一个字符串、字符串是什么以及它有多长)。

它应该返回的查询结果只是数据库中的一个条目

PHP的相关部分是这样的:

   $body = json_decode($param, true);
   $recieved = $body["data"];

您尝试将 $param 解析为 JSON(失败,因为 getResults 不是有效的 JSON)。然后,您尝试从中读取 data 属性(失败,因为它从来没有)。

如果要进行数据库查询,则需要实际查询数据库。

如果此时你想要一些输出,那么你需要提供一些输出。


旁白:

datatype: "application/json",
  • 该属性称为dataType 而不是datatype
  • 它接受值"json",而不是"application/json"
  • PHP 当前返回无法解析为 JSON 的纯文本(尽管它具有 text/html 内容类型,因为您尚未覆盖它)

【讨论】:

  • 希望您不要介意编辑。看里面关于它的评论。编辑:不是我在这里投反对票,不知道你为什么会这样。
  • @Fred-ii- — 这听起来像是一个更好的提议作为引号的样式表更改。 &gt; 已将其标记为引用材料。
  • 好的,抱歉。我有在引用某人时使用引号的习惯,这对我来说很有意义:“To be or not to be...” - William Shakespeare ;-) 编辑:请参阅我对 Quentin 的评论; -) @BenM
  • @Fred-ii- 我同意昆汀的观点,引用的材料不需要强调(所以使用&lt;em&gt;,而不是&lt;i&gt;)。
【解决方案3】:

确保在页面上回显 anything 之前设置 Content-type 标头:

header('Content-Type: application/json; charset=UTF-8');

这样客户端就知道期待 JSON。

【讨论】:

  • 由于 PHP 不输出 JSON,在这个阶段告诉浏览器期待 JSON 会适得其反。
  • 仅当if (empty($param)) 为真时,它不是
  • (或者如果$dao-&gt;openConnection()返回false)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多