简单的前端控制器导致 php 中的 css 和 javascript 损坏
我正在尝试在 php 中实现一个简单的前端控制器.. 在我的index.php中;
$parts = array_slice(explode('/',$_SERVER["REQUEST_URI"]),3);
if(file_exists($parts[0].'.php'))
include $parts[0].'.php';
else
echo 'not found';
所以我输入了地址栏 localhost/myroot/index.php/home,我希望包括 home.php。 它包含 home.php 但没有外部 css 文件和 javascript 源。它们都没有加载。
在 home.php 中,
<link rel="stylesheet" type="text/css" href="styles/master.css" />
<script type="text/javascript" src="scripts/master.js"></script>
根目录有样式和脚本目录 /myroot/styles/master.css /myroot/scripts/master.js
因此,如果我输入 localhost/myroot/home.php,它就会正常工作。
I'm trying to implement a simple front controller in php..
In my index.php;
$parts = array_slice(explode('/',$_SERVER["REQUEST_URI"]),3);
if(file_exists($parts[0].'.php'))
include $parts[0].'.php';
else
echo 'not found';
so i typed the adress bar localhost/myroot/index.php/home, I expect to include home.php.
It's include home.php but without external css files and javascript sources.. None of them are loaded..
in home.php,
<link rel="stylesheet" type="text/css" href="styles/master.css" />
<script type="text/javascript" src="scripts/master.js"></script>
root directory has styles and scripts directories
/myroot/styles/master.css
/myroot/scripts/master.js
so if i type localhost/myroot/home.php, it works correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
停止在 CSS 和 JS 中使用相对 URL
Stop using relative URLs for your CSS and JS
扩展 teresko 的答案...
浏览器不知道(或关心)您的 URL 的形式。当您对 CSS 和 JavaScript 使用相对路径时,它期望它们相对于最后一个目录。
因此,如果您的页面位于
/somecontroller/somepage/someparamater
,并且您引用/scripts/master.js
,那么浏览器将请求/somecontroller /somepage/someparameter/scripts/master.js
。解决方案是简单地将
/
放在这些路径前面,以便它们相对于站点根目录。To expand on teresko's answer...
The browser doesn't know (or care) what form your URLs are in. When you use a relative path for your CSS and JavaScript, it expects them to be relative to the last directory.
So, if your page is at
/somecontroller/somepage/someparamater
, and you reference/scripts/master.js
, then the browser is going to request/somecontroller/somepage/someparameter/scripts/master.js
.The solution is to simply put a
/
in front of those paths so that they are relative to the site root.