【问题标题】:Why isnt my HTML code rendering after running a php function in another file?为什么在另一个文件中运行 php 函数后我的 HTML 代码没有呈现?
【发布时间】:2023-04-07 08:43:01
【问题描述】:

我正在尝试让 API 与我的网站一起使用。该网站混合使用 HTML 和 PHP。这利用引导程序进行布局。我有 3 个 PHP 文件创建数据库链接,查询数据库,将信息放入数组中,将其转换为 JSON 并将其传递给我的索引。然后我的索引应该将数据排序到引导框架中。目前,当我调用该方法获取数据时,html会停止在索引上呈现而不会出错。

Gyazo 目前页面的样子:https://gyazo.com/a090e6327d91187797a825d6dbf77347

我已经编辑了排序代码,因为无论是否包含 html,它都会停止呈现。在 index 的 PHP 段中,似乎是:

$jsonData = $read->getData();?>

是导致问题的原因,尽管我无法找出原因,即使使用 try/catch 语句也是如此。

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet"     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script     src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
  <body>  
    <h1>Hello, world!</h1>

    <div class="container">
        <div class="row">
            <div class="col-3">
                <h3>Name</h3>
            </div>
            <div class="col-3">
                <h3>Price</h3>
            </div>
            <div class="col-3">
                <h3>Description</h3>
            </div>
            <div class="col-3">
                <h3>Image</h3>
            </div>
        </div>
    <?php
    include_once 'API/product/read.php';
    $read = new Read();
    $jsonData = $read->getData();?>

    </div>


<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script     src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">    </script>
    <!-- Include all compiled plugins (below), or include individual files     as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

包含的read.php

<?php
class Read{

    public function getData(){
        try
        {
            // required headers
            header("Access-Control-Allow-Origin: *");
            header("Content-Type: application/json; charset=UTF-8");

            // include database and object files
            include_once 'API/config/database.php';
            include_once 'API/objects/product.php';

            // instantiate database and product object
            $database = new Database();
            $db = $database->getConnection();

            // initialize object
            $product = new Product($db);

            // query products
            $stmt = $product->read();
            $num = $stmt->rowCount();

            // check if more than 0 record found
            if($num>0){

                // Passed array array
                $products_arr=array();

                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                    // extract row
                    // this will make $row['name'] to
                    // just $name only
                    extract($row);

                    $product_item=array(
                        "id" => $Id,
                        "name" => $Name,
                        "price" => $Price,
                        "description" => html_entity_decode($Description),
                        "imageURL" => $ImageURL,
                    );
                    array_push($products_arr, $product_item);
                }
                return json_encode($products_arr);
            }

            else{
                echo json_encode(
                    array("message" => "No products found.")
                );
            }
        } catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }
    }
}
?>

read.php中包含的database.php

<?php
class Database{

    // specify database credentials
    private $host = "localhost";
    private $db_name = "webtestdb";
    private $username = "root";
    private $password = "";
    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" .         $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?> 

最后,product.php 也包含在 read.php 中

<?php
class Product{

    // database connection and table name
    private $conn;
    private $table_name = "unit21";

    // object properties
    public $id;
    public $name;
    public $price;
    public $description;
    public $imageURL;

    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }

    // read products
    function read(){

        // select all query
        $query = "SELECT
                    *
                FROM
                    ".$this->table_name
                    ;

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // execute query
        $stmt->execute();

        return $stmt;
    }
}
?>

【问题讨论】:

  • 目前它不会“输出”任何东西,除非我误解了你? $read->getData() 返回一个 json_encoded 数组
  • $jsonData = $read-&gt;getData(); 不会向页面输出任何内容。它只是为变量赋值。不过,目前尚不清楚您预期会发生什么。 “将数据排序到引导框架中”实际上没有任何意义。大概你想以某种方式在页面上显示这些数据?为此,您需要编写更多代码来处理数据并创建一些 HTML。顺便说一句,除非您打算使用 ajax,否则将数据编码为 JSON 并没有多大意义。如果您想使用 PHP 渲染它,请将其保留为 PHP 对象,否则您只需要再次解码才能使用它
  • P.S.您已经在页面上包含了 jQuery(两个不同的版本!)和 Bootstrap 两次。这充其量是毫无意义的,在最坏的情况下,可能会导致奇怪的冲突错误。您只需要页面中包含的每个库的一份副本。
  • 如果这是您得到的输出,您的网络服务器似乎不理解该页面是 HTML 而不是纯文本
  • 好的,header("Content-Type: application/json; charset=UTF-8"); 告诉网络浏览器 整个页面 的输出内容将是 JSON 格式而不是 HTML。因此,它有效地将其视为文本,而不是解析 HTML。你的导师有没有给你提供那段代码?如果是这样,我认为他们打算让您使用 ajax 解决方案,例如 Rafael 在下面的回答。但是将这种指令放在类方法中是一个坏主意,它不应该以这种方式控制页面级功能。也许解决方案的一部分是删除标题?

标签: php html mysql json


【解决方案1】:

线

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

告诉网络浏览器整个页面的输出内容将是 JSON 格式而不是 HTML。因此,它有效地将其视为文本,而不是解析 HTML。这就是为什么您会看到您的 HTML 代码只是转储到页面上,而不是被浏览器处理成可用的网站。

如果您的脚本的整个输出将是一些 JSON,并且其中没有其他内容,则您只会使用此标头 - 例如就像对 API 调用的响应,而不是面向用户的网页。

你也可以删除

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

因为这仅在您创建一个 API 方法时才需要,该方法将通过 AJAX 从另一个域调用(它启用跨域 (CORS) 请求)。在这种情况下它没有任何意义,并且还会打开一个不必要的安全漏洞。

【讨论】:

    【解决方案2】:

    创建新文件:

    ajax.php
    <?php
        include_once 'API/product/read.php';
        $read = new Read();
        return $read->getData();
    ?>
    

    index.php 中的javascript:

    $(function(){
       $.get('ajax.php', {}, function(response) {
        $.each(response, function(i, k) {
            $('.container').append('<div class="product row" data-id="' + k.id + '"><div class="col-3">' + k.name+'</div><div class="col-3">' + k.price + '</div><div class="col-3">' + k.description + '</div><div class="col-3"><img src="' + k.imageURL + '" title="" alt=""></div></div>');
        });
       }, 'json'); 
    });
    

    你包含了 2 次 jquery 和 bootstrap,删除了一次。

    编辑:

    因为您只需要 PHP 中的解决方案:

    $jsonData = json_decode($read->getData()); 
    foreach ($jsonData as $json) { 
        echo '<div class="product row" data-id="' . $json->id . '"><div class="col-3">' . $json->name . '</div><div class="col-3">' . $json->price . '</div><div class="col-3">' . $json->description . '</div><div class="col-3"><img src="' . $json->imageURL . '" title="" alt=""></div></div>'; 
    }
    

    【讨论】:

    • 这仍在将我使用的语言更改为 JS,或者要求我同时使用 JS 和 PHP 编写来解决问题。导师说这个不用JS就可以完成。
    猜你喜欢
    • 1970-01-01
    • 2022-07-11
    • 1970-01-01
    • 2015-07-21
    • 2019-03-12
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多