2017-10-19 37 views
0

我正在尝试使用我的网站的API。该网站使用了HTML和PHP的组合。这使得bootstrap用于布局。我有3个PHP文件创建数据库链接,查询数据库,将信息放入数组中,将其转换为JSON并传递给我的索引。我的索引应该将数据分类到引导框架中。目前,当我调用获取数据的方法时,html会停止在索引上渲染而不会出错。为什么我的HTML代码在另一个文件中运行php函数后呈现?

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

我有删节排序的代码,如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; 
    } 
} 
?> 
+0

下面句子的输出是什么$ jsonData = $ read-> getData(); –

+1

目前它不“输出”任何东西,除非我误解你? $只读>的getData()返回一个json_encoded阵列 – Illuminite

+0

下面是一些JSON数据的gyazo,我有一个镀铬的插件,使得它看起来更漂亮,更具可读性 https://gyazo.com/abac22f03d568d1759922bec8b5df2d0 – Illuminite

回答

1

线

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

告诉整个页面的输出内容是要在网络浏览器采用JSON格式而不是HTML。所以它将它视为文本,而不是解析HTML。这就是为什么你看到你的HTML代码刚刚转储到页面上,而不是被浏览器处理成可用的网站。

如果脚本的整个输出将会是某个JSON,并且其中没有其他内容(例如,比如对API调用的响应,而不是面向用户的网页。

您还可以删除

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

,因为如果你正在做这将通过AJAX从另一个域调用的API函数,这是唯一需要(它允许跨域(CORS)的请求)。在这种情况下没有意义,也会造成不必要的安全漏洞。

1

创建新的文件:

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

的JavaScript的index.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'); 
}); 

你包括2次jQuery和引导,去掉一个。

编辑:

因为你只想要在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>'; 
} 
+0

这仍然在改变使用JS的语言,或者要求我写JS和PHP来解决这个问题。我的导师说过,这可以在不需要使用JS的情况下完成。 – Illuminite

相关问题