简体   繁体   中英

Loading External js File in PHP Class

In a php class, assuming the js file is in the same directory, but I can never predict where the two files will be located on the server, how do I make sure the js file is properly referenced?

This doesn't work at all:

    function import_script() {
    ?>
        <script src="<?php echo(__DIR__); ?>\myscriptfile.js"></script>

I hope this is clear enough - enough code foryou to see what I'm trying to do. Feel free to request more and I'll edit the question.

You don't need to do any of the fancy coding just put a . before the first slash like this:

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

When getting directory listings, you notice there is . and .. , . indicates current directory, while .. indicates the parent directory. All without having to know the current directories name, so you could change it every hour, the script would work then same.

This is a simple question with a vast answers. Keeping your assets in relative directory or absolute, might require some knowledge on your framework, but simply:

function import_script() {
?>
    <script src="myscriptfile.js"></script>

if you are pretty sure it's located same directory as your php url file.

You can even try this

function import_script() {
    echo "<script src='".__DIR__."/myscriptfile.js'></script>";
}

For more reference check this SO question how to write HTML inside PHP

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