繁体   English   中英

js 文件正在加载,但 css 文件未加载

[英]js file is loading but css file is not loading

In my index.html file js file is loading but css file is not, after debugging in access_log file I found that server sends css file with 200 response but my html file is not loading that.

I redirected all requests to index.php on my server using .htaccess file, then, I tried to get css file directly with url and it is working fine.

接下来,我在localhost环境中工作。 我有主htdocs文件夹,它包含所有文件index.phpindex.html 另外,它包含资产文件夹,其中放置了我的 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]

如果你使用 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'; ?>">

after very hard searching on web i found that you have to set content type first before sending any data to html so before sending css or js file i have to set content type on header header('Content-type: text/css'); 所以我更改了 index.php 文件中的逻辑,以对不同的数据类型做出不同的响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM