【问题标题】:js file is loading but css file is not loadingjs 文件正在加载,但 css 文件未加载
【发布时间】:2021-05-18 12:38:38
【问题描述】:

在我的index.html 文件中,js 文件正在加载但 css 文件未加载,在 access_log 文件中调试后,我发现服务器发送的 css 文件响应为 200,但我的 html 文件没有加载。

我使用.htaccess文件将所有请求重定向到我服务器上的index.php,然后,我尝试直接使用url获取css文件,它工作正常。

接下来,我在localhost 环境中工作。我有主要的htdocs 文件夹,它包含所有文件index.phpindex.html;此外,它还包含 assets 文件夹,其中放置了我的 js 和 css 文件。

html 文件:

<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link media="all" rel="stylesheet" href="/assets/test.css" type="text/css" />
  <title>Chat</title>
</head>
<body>
  <div class="top_bar">
    <h1 id="status"></h1>
  </div>
  <div id="test" class="wrapper">
  </div>
  <div class="bottom_bar">
    <form class="text" onsubmit="onEnter(); return false" autocomplete="off">
      <input type="text" name="text" placeholder="Type here" id="text" />
    </form>
    <button id="send">
    </button>
  </div>
  <script src="assets/chat.js"></script>
</body>

我的 index.php 文件:

<?php

$raw_url = $_SERVER['REQUEST_URI'];

$url = explode('?', $raw_url);

$route = $url[0];

$query = $url[1];

if (substr($route, 0, 8) == '/assets/') {
  $file_name = substr($route, 8);
  if(file_exists('assets/' . $file_name)) {
    readfile('assets/' . $file_name);
  }
  else {
    http_response_code(404);
  }
} else {
  switch ($route) {
    case '/':
      readfile('index.html');
      break;
    default:
      http_response_code(404);
      break;
  }
}
?>

.htaccess 文件:

RewriteEngine on
RewriteRule (.*) index.php
RewriteRule ^assets/ - [L,NC]

【问题讨论】:

  • /assets 改为assets
  • 我试过了,但没有任何改变

标签: javascript php html css apache


【解决方案1】:

如果你使用 CodeIgniter,你可以这样使用

PHP

$server_addr = $_SERVER['SERVER_ADDR'];
$base_url = (is_https() ? 'https' : 'http').'://'.$server_addr
.substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME'])));
$this->set_item('base_url', $base_url);

html

<link rel="stylesheet" href="<?php echo base_url().'/assets/test.css'; ?>">

【讨论】:

    【解决方案2】:

    在网络上进行了非常艰苦的搜索后,我发现您必须先设置内容类型,然后才能将任何数据发送到 html,因此在发送 css 或 js 文件之前,我必须在标题 header('Content-type: text/css'); 上设置内容类型,所以我更改了索引中的逻辑.php 文件以对不同的数据类型做出不同的响应。

    【讨论】:

      猜你喜欢
      • 2015-10-08
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 2019-06-07
      • 2019-04-05
      • 2018-02-28
      • 1970-01-01
      相关资源
      最近更新 更多