为什么在另一个文件中运行php函数后我的HTML代码不呈现?
我正在尝试让API与我的网站一起工作。该网站混合使用HTML和PHP。这使得布局使用引导。我有3个PHP文件创建数据库链接、查询数据库、将信息放入数组、将其转换为JSON并将其传递给我的索引。然后,我的索引应该将数据排序到引导框架中。目前,当我调用该方法获取数据时,html会在索引上停止呈现,不会出错 当前页面外观的Gyazo: 我已经修改了排序代码,因为不管是否包含html,html都会停止呈现。在索引的PHP段中,似乎:为什么在另一个文件中运行php函数后我的HTML代码不呈现?,php,html,mysql,json,Php,Html,Mysql,Json,我正在尝试让API与我的网站一起工作。该网站混合使用HTML和PHP。这使得布局使用引导。我有3个PHP文件创建数据库链接、查询数据库、将信息放入数组、将其转换为JSON并将其传递给我的索引。然后,我的索引应该将数据排序到引导框架中。目前,当我调用该方法获取数据时,html会在索引上停止呈现,不会出错 当前页面外观的Gyazo: 我已经修改了排序代码,因为不管是否包含html,html都会停止呈现。在索引的PHP段中,似乎: $jsonData = $read->getData();?&g
$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;
}
}
?>
<?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;
}
}
?>
最后,product.php也包含在read.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;
}
}
?>
<?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;
}
}
?>
创建新文件:
ajax.php
<?php
include_once 'API/product/read.php';
$read = new Read();
return $read->getData();
?>
ajax.php
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');
});
$(函数(){
$.get('ajax.php',{},函数(响应){
$。每个(响应、功能(i、k){
$('.container')。追加(''+k.name+''+k.price+''+k.description+'');
});
}“json”);
});
您包含了两次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>';
}
$jsonData=json_decode($read->getData());
foreach($jsonData作为$json){
回声'.$json->name'.$json->price'.$json->description.'imageURL'.“title=”“alt=”“>”;
}
创建新文件:
ajax.php
<?php
include_once 'API/product/read.php';
$read = new Read();
return $read->getData();
?>
ajax.php
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');
});
$(函数(){
$.get('ajax.php',{},函数(响应){
$。每个(响应、功能(i、k){
$('.container')。追加(''+k.name+''+k.price+''+k.description+'');
});
}“json”);
});
您包含了两次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>';
}
$jsonData=json_decode($read->getData());
foreach($jsonData作为$json){
回声'.$json->name'.$json->price'.$json->description.'imageURL'.“title=”“alt=”“>”;
}
线路
header("Content-Type: application/json; charset=UTF-8");
正在告诉web浏览器整个页面的输出内容将采用JSON格式而不是HTML格式。因此,它有效地将其视为文本,而不是解析HTML。这就是为什么你看到你的HTML代码只是被转储到页面上,而不是被浏览器处理成一个可用的网站
如果脚本的整个输出都是JSON,而没有其他内容,例如对API调用的响应,而不是面向用户的网页,则只会使用此标题
您还可以删除
header("Access-Control-Allow-Origin: *");
因为这只在您创建一个API方法时才需要,该方法将通过AJAX从另一个域调用(它支持跨源(CORS)请求)。在这种情况下,它毫无意义,而且还打开了一个不必要的安全漏洞。
header("Content-Type: application/json; charset=UTF-8");
正在告诉web浏览器整个页面的输出内容将采用JSON格式而不是HTML格式。因此,它有效地将其视为文本,而不是解析HTML。这就是为什么你看到你的HTML代码只是被转储到页面上,而不是被浏览器处理成一个可用的网站
如果脚本的整个输出都是JSON,而没有其他内容,例如对API调用的响应,而不是面向用户的网页,则只会使用此标题
您还可以删除
header("Access-Control-Allow-Origin: *");
因为这只在您创建一个API方法时才需要,该方法将通过AJAX从另一个域调用(它支持跨源(CORS)请求)。在这种情况下,它毫无意义,而且还打开了一个不必要的安全漏洞。目前它没有“输出”任何内容,除非我误解了你$read->getData()返回一个json_编码的数组
$jsonData=$read->getData()代码>不向页面输出任何内容。它只是给变量赋值。不过,还不清楚你预期会发生什么。“将数据排序到引导框架中”实际上没有任何意义。您可能想以某种方式在页面上显示这些数据?为此,您需要编写更多的代码来处理数据并创建一些HTML。顺便说一句,除非您计划使用ajax,否则将数据编码为JSON没有多大意义。如果你想用PHP呈现它,那么就把它作为一个PHP对象,否则你只需要再次解码它就可以使用itP.S了。您已经在页面上包含了两次jQuery(两个不同的版本!)和Bootstrap。这在最好的情况下是毫无意义的,在最坏的情况下,可能会导致奇怪的冲突错误。您只需要页面中包含的每个库的一个副本。如果这是您得到的输出,那么您的Web服务器似乎不理解页面是HTML而不是纯文本OK,标题(“内容类型:application/json;charset=UTF-8”)
告诉web浏览器整个页面的输出内容将是JSON格式而不是HTML格式。因此,它有效地将其视为文本,而不是解析HTML。你们的导师给你们提供了那个些代码吗?如果是这样的话,我想他们打算让你使用一个ajax解决方案,就像下面Rafael的答案一样。但是将这种指令放在类方法中是个坏主意,它不应该以这种方式控制页面级功能。也许部分解决方案是删除标题?目前它没有“输出”任何东西,除非我误解了