php - AngularJS:为单个帖子制作页面
问题描述
我正在用 AngularJS 制作一个博客应用程序。我有一个主页,显示所有帖子,但我也希望能够单击帖子并转到其页面。数据存储在 MySQL 数据库中。
主页上显示的帖子:
<ul>
<li ng-repeat="post in posts track by $index" id="content">
<h1><a href="#!/post/{{post.id}}">{{ post.title }}</a></h1>
</br>
<h2>{{ post.content }}</h2>
</li>
</ul>
单个帖子的页面:
<h1>{{ post.title }}</h1>
</br>
<h2>{{ post.content }}</h2>
在 addremove.php 中通过 PHP 获取数据(由主页使用):
if($request_type == 1){
$stmt = $con->prepare("SELECT * FROM posts");
$stmt->execute();
$result = $stmt->get_result();
$data = array();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$data[] = array("id"=>$row['id'],"title"=>$row['title'],"content"=>$row['content']);
}
}
$stmt->close();
echo json_encode($data);
exit;
}
通过主页控制器(HomeController)传递的数据:
$http({
method: 'post',
url: 'addremove.php',
data: {request_type:1},
}).then(function successCallback(response) {
$scope.posts = response.data;
});
我在使用单个帖子的控制器 (SinglePostController) 时遇到问题。我不知道如何通过它的 id 只显示一个帖子。我尝试了以下方法:
blogApp.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$http({
method: 'post',
url: 'getSinglePost.php',
data: {
request_type:1,
id: $routeParams.postid
},
}).then(function successCallback(response) {
$scope.posts = response.data;
});
}]);
我制作了一个 getSinglePost.php 文件,如下所示:
<?php
include 'config.php';
$post = json_decode(file_get_contents("php://input"));
$id = $post->id;
$request_type = $data->request_type;
if($request_type == 1){
$stmt = $con->prepare("SELECT * FROM posts");
$stmt->execute();
$result = $stmt->get_result();
$data = array();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$data[] = array("id"=>$row['id'],"title"=>$row['title'],"content"=>$row['content']);
}
}
$stmt->close();
echo json_encode($data);
exit;
}
?>
解决方案
主页
- 帖子 1
- 帖子 2
当我单击post 2
时,它转到 /#/!/post/2
在单张贴状态配置中
$routeProvider.when('/post/:postid', {
// this is how to set the variable for the post id
controller: 'SinglePostController'
在单个博客页面控制器中
blogApp.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$http({
method: 'post',
url: 'getSinglePost.php',
data: {
request_type:1,
id: $routeParams.postid
},
}).then(function successCallback(response) {
$scope.post = response.data;
});
然后在你的 PHP
<? // getSinglePost.php
$post = json_decode(file_get_contents("php://input"));
$id = $post->id;
// get single blog info from database and echo it back with json_encode()
推荐阅读
- python - 从 Windows shell 调用 Anaconda Python 时导入失败
- python - 如何从响应中删除 u(unicode) 并使用机器人框架在正文中替换它?
- strapi - Strapi 关系的 POST 详细信息
- .net - Azure 服务总线 - 更新锁无法正常工作
- javascript - 如何在 ReactJS 中渲染嵌套数据?
- sql-server - Active Directory 组的 SqlTableDependency 权限问题
- css - 如何修复顶部导航栏粘滞位置?
- .net-core - Raspberry Pi 4 上 Visual Studio 2019 CE 的 Dotnetcore 3.0 远程调试 - 权限不足
- ruby-on-rails - 如何在 rake 任务中读取 csv 文件
- excel - VBA:如何知道图表是否在单独的工作表中?