简体   繁体   中英

CSS and JS won't load even when in same directory as index.php

I feel like I must be missing something very obvious, because I've never had this happen before!

I'm running a local PHP server running the following command:

php -S localhost:8888 index.php

When I go to the URL, the HTML and all the php code run just fine.

However, whenever I add a script tag to add JS in the header, I recieve the following error:

Uncaught SyntaxError: Unexcepted token <

And when I attempt to add a CSS file I get this error:

Resource interpreted as Stylesheet but transferred with MIME type text/html: " http://localhost:8888/assets/style.css ".

No matter whether I try and include the header by using PHP include :

<?php include("../includes/layouts/header.php"); ?>

Or directly adding a header and these imports in index.php , I always receive these errors.

My hunch was it was an issue with the directory tree. But I've even placed the CSS and JS files in the same directory as index.php and have added the header code to index.php , yet I still get these errors.

Header code

<!DOCTYPE html Public "HTML TEMPLATE">
<html lang="en">
<head>
    <title>Title</title>
    <link rel="stylesheet" href="style.css" media="all" title="no title" type="text/css" charset="utf-8">
    <script src="script.js"></script>
</head>
<body>
<div id="header">
    <h1>Header</h1>
</div>

script.js:

$( document ).ready(function() {
    console.log( "ready!" );
});

Console log of errors:

控制台错误

Adding an image of my current project structure:

在此处输入图片说明

you should used / at the start of the path. as per your update question your path become /public/assets/style.css . but again i recommend you should used best way

link rel="stylesheet" href="/public/assets/style.css" media="all" title="no title" type="text/css" charset="utf-8">
    <script src="/public/assets/script.js"></script>

Some more information about absolute path and relative path

  • If the path is built starting from the system root, it is called absolute.
  • If the path is built starting from the current location, it is called relative

The best way: you should create base url like in config.php file

define('BASE_URL', 'http://example.com');

and you can used like this

<?php
    include('config.php');
?>

<link rel="stylesheet" href="<?php echo BASE_URL; ?>/styles.css" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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