dswqz24846 2013-09-05 06:54
浏览 124
已采纳

包括基于URL的javascript文件

i have an application in which i have created a header.php which is obviously common for all the pages in the app which i include on top of every other page. This header file contains the html head tags and DOCTYPE declaration etc and some common JS and CSS files needed for every page. But there are some specific files which i want to include depending on the page.

Now, how do i include a specific JS or CSS file based on the url from which the header.php is requested.

I tried to use $_SERVER['PHP_SELF'] at the top of header file to fetch the url but it did not work.

Please suggest with the best technique that should be used in this situation.

Sample Code

header.php

 <?php
 include (dirname(__FILE__) . "/includes/functions.php");
 $url = $_SERVER['REQUEST_URI'];
  ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>My APP</title>
<meta charset="utf-8" />
<meta name="robots" content="noodp, noydir" />
<meta http-equiv="X-Frame-Options" content="deny" />
<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src="js/main.js"></script>
<?php
if($url == "teachers.php"){
echo "<script src='js/teachers.js'></script>";
   }  
?>

</head>
<body>
  • 写回答

3条回答 默认 最新

  • dpjhq00684 2013-09-05 06:59
    关注

    The array you are looking for is the superglobal $_SERVER. It has all that info. More specifically: $_SERVER['REQUEST_URI'].

    $_SERVER['REQUEST_URI'] gives the complete path, including slashes and any GET request. In your case (if teachers.php is in your server's root, and you don't GET anything), it will hold /teachers.php, and you are comparing against teachers.php.

    $_SERVER['SCRIPT_FILENAME'] gets the executing script, which is what you seem to be looking for.

    You could use basename to filter the path out:

    $url = basename($_SERVER['SCRIPT_FILENAME']);
    

    By the way, @hendyanto's solution is also good. It is certainly robust against filename changes.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分