为什么在另一个文件中运行php函数后我的HTML代码呈现?

时间:2017-10-19 11:35:37

标签: php html mysql json

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

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

我已经编辑了排序代码,因为无论是否包含html,html都会停止渲染。在索引的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;
    }
}
?>

2 个答案:

答案 0 :(得分:1)

创建新文件:

class ListItemProvider {
    public getItems(requester: SPHttpClient, siteUrl: string): IListItem[] {
        // Just the code for list items
        return [];
    }
}

class NewsItemProvider {
    public getItems(requester: SPHttpClient, siteUrl: string): INewsListItem[] {
        // Just the code for news items
        return [];
    }
}

class AnnouncementItemProvider {
    public getItems(requester: SPHttpClient, siteUrl: string): IAnnouncementListItem[] {
        // Just the code for announcment items
        return [];
    }
}


class Example {
    public getItemProvider(listName: 'News'): NewsItemProvider;
    public getItemProvider(listName: 'Announcments'): AnnouncementItemProvider;
    public getItemProvider(listName: 'List' | 'News' | 'Announcments'): ListItemProvider;
    public getItemProvider(listName: 'List' | 'News' | 'Announcments') : ListItemProvider {
        switch (listName) {
            case 'List':
                return new ListItemProvider();
            case 'News':
                return new NewsItemProvider();
            case 'Announcments':
                return new AnnouncementItemProvider();
            default:
                throw new Error('No provider for ' + listName);
        }
    }
}

const example = new Example();

// INewsListItem[]
const news = example.getItemProvider('News').getItems(null, '');

// IAnnouncementListItem[]
const announcements = example.getItemProvider('Announcments').getItems(null, '');

index.php中的javascript:

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

你包括2次jquery和bootstrap,删除一个。

编辑:

因为您只想在PHP中使用解决方案:

$(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'); 
});

答案 1 :(得分:1)

该行

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

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

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

您也可以删除

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

因为只有在你创建一个API方法时才需要这个,这个方法将通过另一个域的AJAX调用(它启用了跨域(CORS)请求)。在这种情况下没有任何意义,也会带来不必要的安全漏洞。