user3310334
user3310334

Reputation:

JavaScript request relative page, treat current page as directory

On the page /document/1 the request $.getJSON('./json', ... requests /document/json

I would like to request /document/1/json

Is there a way I can resolve a path to this without needing to manually read and append to the URL?

Upvotes: 1

Views: 31

Answers (1)

D. Pardal
D. Pardal

Reputation: 6597

Your issue is that ./ is relative to the current directory, and in the path /document/1, the directory is /document, which contains a "file" named 1.

You can solve this by adding a trailing slash to the URL (/document/1/). In that case, the address is interpreted as the index of the /document/1 directory.

Or you can use the Location API:

$.getJSON(window.location.pathname + '/json', /* ... */);

You can also add the trailing slash with JS:

if (!window.location.pathname.endsWith("/")) {
    const url = new URL(location);
    url.pathname += "/";
    window.history.replaceState(null, "", url);
}

Upvotes: 1

Related Questions