0

I would like to avoid JavaScript in my HTML/PHP-Templates. Everything is working fine as long as I don't need a base/root-URL in my external, included JS-File.

Problem: Does anybody know a solution to put the JS logic (code below) into an external JS file? The main problem: how to figure out the _BASE_URL_? Unfortunately its not a form where you can get the URL by the action-attribute. I dont want to compile JS/PHP-mixed files, it has to be pure JS.

Idea (too dirty): A hidden input in the top of the body-tag with id="root_url" or a variable in the main JS file: root_url = "http://localhost/projects/project/version/". This is prone to failure, because no file could work stand-alone.

Maybe there's a good htaccess/mod_rewrite solution?

Notice: I dont want to get the hostname or the "real" root dir, because it has to work in subfolders as well!

Code:

<script type="text/javascript">
// document ready
$(function() {
    // function: load items
    function load_items() {
        $("#items").load("<?php echo _BASE_URL_?>/items.php");
    }

    // load items!
    load_items();
});
</script>

<!-- target div --> 
<div id="items">loading</div>

Thanks in advance!

2 Answers 2

3

Can i see your html structure

function getBaseURL () {
   return location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
}

if you need a path also use this

path = window.location.pathname.split( '/' );
console.log(path);
Sign up to request clarification or add additional context in comments.

1 Comment

Your function would work better with something like this: stackoverflow.com/a/11775016/1431728.
0

can we use like this

function getBaseURL () {
    return location.protocol + "//" + location.hostname + location.pathname;


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.