简体   繁体   中英

How to link external .js file in .php file

I am trying to simply call a JavaScript function that is found an external file. My folder structure is:

C:\\xampp\\htdocs\\test\\index.php

C:\\xampp\\htdocs\\test\\js\\functions.js

index.php

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="profile" href="http://gmpg.org/xfn/11">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="css/stylesheet.css"/>
    <title>Home</title>
  </head>

  <body>
    <?php include("header.php"); ?>
    <?php include("content.php"); ?>

    <script src="https://kit.fontawesome.com/f0aaae8537.js"></script>
    <script src="/js/functions.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>

  <script>
    test();
   </script>
</html>

functions.js

function test(){
   alert("where am i");
}

I am using VS Code and XAMPP. The function test is not being called. It works when I define the function inside index.php but not in the external file. I have tried including the attribute type="text/javascript" and moving the functions.js file to the root folder "test" but still nothing.

Most likely, js is not in the root folder and therefore you script tag may need to be:

<script src="js/functions.js"></script>

Note the absence of / before js .

Try This

<script src="js/functions.js"></script>

In functions.js

$(document).ready(function() {
   function test(){
     alert("where am i");
   }
});

删除/否则它将被视为从/ (运行文件的根目录,很可能是Web服务器)开始的路径:

<script src="js/functions.js"></script>

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