简体   繁体   中英

Use jQuery to load HTML from external file at absolute path

I am trying to load the content of an external HTML file into my current HTML template.

The problem I'm running into is that the content I want to load is not local, and it's not at a URL. The file is on a central storage directory that I can access while connected to a VPN. In other words, if all my local files are within /Users/username/... , then this file is at /central_directory/absolute/path/to/file.html .

I can access the file at /central_directory/absolute/path/to/file.html from the Terminal or at file:///central_directory/absolute/path/to/file.html from within my browser.

However, when I try to load the file using the jQuery .load() function, I get a 404 not found error:

Not Found: /central_directory/absolute/path/to/file.html

[15/Jul/2018 19:04:22] "GET /central_directory/absolute/path/to/file.html HTTP/1.1" 404 2257

My guess is that it's not looking in the right place for the file (eg it is looking at http://mywebsite/central_directory/absolute/path/to/file.html ), but I don't know if this is an accurate guess, or how to test.


Code:

Here is the jQuery script, in the head of my current template:

<script>
    $(function(){
        var filename = "file:///central_directory/absolute/path/to/file.html"
        $("#includedContent").load(filename);
    });
</script>

and the HTML in the template:

<div id="includedContent"></div>

Simple enough, right?

I have also tried other syntax, with the same 404 error occurring.

The problem is that .load() requires an HTTP connection (so a GET or POST request) for javascript.

This is the fortunate result of the fact that you cannot load a javascript resource in the same way you can navigate to a file:// path in your browser or terminal ('fortunate' because it prevents anybody from accessing any file on your computer).

The only real way to get around this is by having the local file proxied through a web server to your browser (so you'll need to have control over the server implementation). If you have an existing web server stack (like PHP , Node.js , Ruby , etc) you can very likely do this, but it ultimately depends on what it is.

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