Javascript – Relative and Absolute Path In JavaScript

absolute-pathjavascriptjqueryrelative-path

I have the following very simple code which just reads a JSON file:

<html>
<head>
<meta charset="ISO-8859-1">
<title>JSON Test</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(function()
{
    alert (1);
    $.getJSON('data/sample.json', function(json) 
    {
        alert(2);

    });
});
</script>
</head>
<body>
    <div id="datadiv">This is the info:  </div>
</body>
</html>

I load the above file on a Tomcat server and can load the file using: http://myserver.com:8080/Html5_Test_1/jsonTest.html. The above code works, and alert(2) is called. However, if I change the path that that I use for getJSON to /Html5_Test_1/data/sample.json, it won't work.

I think that /Html5_Test_1/data/sample.json is the absolute path for data/sample.json, and should work. In fact I've tried /data/sample.json, Html5_Test_1/data/sample.json, and none works. The only path that works is data/sample.json.

Can anyone tell me what is wrong? The absolute path /Html5_Test_1/data/sample.json would certainly work in Java. So, is the concept of absolute and relative path a bit different in JavaScript?

Note that the file is being accessed as public file on the server and not as a file on the local file system.

Best Solution

You seem to mix absolute/relative filesystem paths and absolute/relative URLs. Remember, JavaScript is client-side language, it has nothing to do with the filesystem of the server that hosts its master page. So you'd rather put up a relative URL, taking into account that it's starting point will most probably be the path of the served file.

But why it works now, you may ask? Check this:

/Html5_Test_1/
.. data/
.... sample.json
.. jsonTest.html

... and remember, an URL will be taken as related to the directory which contains jsonTest.html file. It's easy to see why proper relative path is data/sample.json (or './data/sample.json').

If you wish, you can change your code to something like this...

$.getJSON('file:///Html5_Test_1/data/sample.json', function(json) ...);

... but this obviously will make it unusable on any other machine than yours.