You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS路由问题:如何根据文章ID从MySQL查询数据

解决AngularJS路由结合MySQL文章查询的方案

我来帮你一步步搞定这个AngularJS路由结合MySQL查询的问题,咱们从前端路由配置到后端接口实现逐个拆解:


1. 配置AngularJS路由与控制器(app.js)

首先要确保你的项目中引入了angular-route.js依赖,然后在app.js里完成路由配置和控制器逻辑:

// 初始化AngularJS应用,依赖ngRoute模块
var app = angular.module('myApp', ['ngRoute']);

// 路由配置
app.config(function($routeProvider) {
  $routeProvider
    // 文章列表页路由
    .when('/posts', {
      templateUrl: 'posts.html',
      controller: 'PostsController'
    })
    // 文章详情页路由,:postId是动态参数,用来传递文章ID
    .when('/read/:postId', {
      templateUrl: 'read.html',
      controller: 'ReadPostController'
    })
    // 默认跳转到文章列表页
    .otherwise({
      redirectTo: '/posts'
    });
});

// 文章列表控制器:获取所有文章数据
app.controller('PostsController', function($scope, $http) {
  $http.get('db.php?action=getAllPosts')
    .then(function(response) {
      // 将返回的文章数据绑定到作用域
      $scope.posts = response.data;
    })
    .catch(function(error) {
      console.error('加载文章列表失败:', error);
    });
});

// 文章详情控制器:根据ID获取单篇文章
app.controller('ReadPostController', function($scope, $http, $routeParams) {
  // 从路由参数中获取文章ID
  var postId = $routeParams.postId;
  
  $http.get('db.php?action=getPostById&id=' + postId)
    .then(function(response) {
      $scope.post = response.data;
    })
    .catch(function(error) {
      console.error('加载文章详情失败:', error);
    });
});

2. 前端页面实现

posts.html(文章列表页)

这个页面负责展示所有文章的标题和作者,点击标题跳转到对应的详情页:

<div ng-controller="PostsController">
  <h2>文章列表</h2>
  <!-- 循环渲染所有文章 -->
  <div ng-repeat="post in posts" style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #eee;">
    <h3>
      <!-- 链接到详情页,传递文章ID -->
      <a href="#!/read/{{post.id}}">{{post.title}}</a>
    </h3>
    <p><strong>作者:</strong> {{post.author}}</p>
  </div>
</div>

read.html(文章详情页)

这个页面展示单篇文章的完整内容:

<div ng-controller="ReadPostController">
  <h2>{{post.title}}</h2>
  <p style="color: #666;"><em>作者: {{post.author}}</em></p>
  <!-- 文章内容区域 -->
  <div style="margin-top: 20px; line-height: 1.6;">{{post.body}}</div>
  <br>
  <!-- 返回列表页的链接 -->
  <a href="#!/posts">← 返回文章列表</a>
</div>

3. 后端数据库接口(db.php)

这个文件负责连接MySQL数据库,处理前端的请求,返回JSON格式的数据,同时注意防护SQL注入:

<?php
// 数据库连接配置,请替换成你自己的数据库信息
$host = 'localhost';
$dbname = '你的数据库名';
$username = '你的用户名';
$password = '你的密码';

try {
  // 初始化PDO连接
  $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // 获取前端传递的action参数
  $action = isset($_GET['action']) ? $_GET['action'] : '';

  switch ($action) {
    case 'getAllPosts':
      // 查询所有文章(只返回id、title、author,减少数据传输)
      $stmt = $pdo->query("SELECT id, title, author FROM posts");
      $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
      echo json_encode($posts);
      break;
    
    case 'getPostById':
      // 获取文章ID并验证合法性
      $postId = isset($_GET['id']) ? intval($_GET['id']) : 0;
      if ($postId <= 0) {
        echo json_encode(['error' => '无效的文章ID']);
        exit;
      }

      // 预处理SQL语句,防止SQL注入
      $stmt = $pdo->prepare("SELECT id, title, body, author FROM posts WHERE id = :id");
      $stmt->bindParam(':id', $postId, PDO::PARAM_INT);
      $stmt->execute();
      $post = $stmt->fetch(PDO::FETCH_ASSOC);

      if ($post) {
        echo json_encode($post);
      } else {
        echo json_encode(['error' => '未找到对应的文章']);
      }
      break;
    
    default:
      echo json_encode(['error' => '无效的请求动作']);
      break;
  }
} catch(PDOException $e) {
  // 捕获数据库异常并返回错误信息
  echo json_encode(['error' => '数据库连接或查询失败: ' . $e->getMessage()]);
}
?>

几个关键注意事项

  • 确保你的主页面(比如index.html)中引入了AngularJS和angular-route的脚本,并且包含<div ng-view></div>来渲染路由模板:
    <!DOCTYPE html>
    <html ng-app="myApp">
    <head>
      <title>AngularJS文章系统</title>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
      <script src="app.js"></script>
    </head>
    <body>
      <div ng-view></div>
    </body>
    </html>
    
  • 替换db.php中的数据库配置信息,确保你的MySQL中存在posts表,且字段为id、title、body、author。
  • 始终使用预处理语句来防止SQL注入,不要直接将用户输入拼接进SQL语句中。

内容的提问来源于stack exchange,提问作者jahangir_kazimli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:40:58