douzhanshen0657 2011-10-06 20:36
浏览 26
已采纳

简单的前端控制器导致PHP中的css和javascript损坏

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.

  • 写回答

2条回答 默认 最新

  • dtz33344 2011-10-06 21:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?