我正在学习在 php 中进行路由。我能够毫无错误地路由页面,但我坚持包含 css
和 js
文件。我在教程和示例中使用的媒体是 laracast 视频。我也在使用 xampp
适用于 Windows 上的 apache 服务器。
我想做自己的练习,下图是我做的文件结构,
在我的 .htaccess
上文件,我有:
RewriteEngine On
RewriteBase /season-temp
RewriteRule ^.*$ index.php [END]
在我的 views 文件夹中,我有所有的 View 页面文件,包括 header
和 footer
包括 css
和 js
.
header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Logo Nav - Start Bootstrap Template</title>
<!-- Bootstrap Core CSS -->
<link href="/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="/css/logo-nav.css" rel="stylesheet">
</head>
<body>
<?php require('navigations.php'); ?>
footer.php
<!-- jQuery -->
<script src="/js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
从上面的代码来看,会报错:
GET http://localhost/css/bootstrap.min.css
GET http://localhost/css/logo-nav.css
GET http://localhost/js/jquery.js
GET http://localhost/js/bootstrap.min.js
我尝试插入 <base href="/">
在 head 部分并在每个 src/href 上建立链接,如 'season-temp/<folder_name>/<file_name>'
,例如; 'season-temp/css/bootstrap.min.css'
但仍然无法获取 css 和 js 文件。
我要如何包含这些文件?
Update - Incorrect output
首先,对于以下解决方案的错误更新表示歉意。 css 和 js 确实有效,但链接已断开。如果我撤消 .htaccess
基于@Triby 答案的文件,链接工作正常但 css 和 js 不是。以下是我的 navigations.php
的页面和 routes.php
navigations.php
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="/season-temp/about">About</a>
</li>
<li>
<a href="/season-temp/services">Services</a>
</li>
<li>
<a href="/season-temp/contact">Contact</a>
</li>
</ul>
</div>
routes.php
<?php
$router->get('season-temp','controllers/index.php');
$router->get('season-temp/about','controllers/about.php');
$router->get('season-temp/services','controllers/services.php');
$router->get('season-temp/contact','controllers/contact.php');
如果我按照@ceejayoz 提到的 css 和 js 文件更新链接,我会收到以下错误:
<br />
<b>Fatal error</b>: Uncaught exception 'Exception' with message
'No route defined for this URI.'
in C:\xampp\htdocs\season-temp\core\router.php:30
Stack trace:
#0 C:\xampp\htdocs\season-temp\index.php(9):
Router->direct('season-temp/js/...', 'GET')
#1 {main}
thrown in <b>C:\xampp\htdocs\season-temp\core\router.php</b>
on line <b>30</b><br />
最佳答案
您正在将所有内容重定向到 index.php,请尝试仅重定向不存在的文件或目录:
RewriteEngine On
RewriteBase /season-temp
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.php [L]
L是当规则匹配时,避免处理下面的任何规则
关于PHP 路由 - 包含 css/js 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45489609/