问题
Searching and reading here got me part way to my solution, which is a workaround for loading a text file using oft recommended code such as:
function FileRead(U)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
X=new XMLHttpRequest();
}
else
{// code for IE6, IE5
X=new ActiveXObject("Microsoft.XMLHTTP");
}
X.open('GET', U, false );
X.setRequestHeader('Content-Type', 'text/html')
X.send();
return X.responseText;
}
This works well for me, so far, on PCs, but not on Macs.
So I used a technique recommended here where I designate the local file as a source in a script, and that worked well for several pages. For the other pages I need to define the source at runtime, taking the path from local storage. Again, tips here helped, but I hit a snag. The following code, located in the header, gets thing rolling.
<script>
var albumPath = '';
if (typeof(Storage) !== "undefined")
{
albumPath = localStorage.getItem('photo_album_path');
}
if (albumPath.substr(albumPath-1,1) !== '/') {albumPath = albumPath +'/'}
var Raw_Album_Info = '';
var script = document.createElement('script');
script.src = albumPath+"album_info.txt";
document.head.appendChild(script);
</script>
<script src="../scripts/common.js" type="text/javascript"></script>
<script src="../scripts/photos_pages.js" type="text/javascript"></script>
<script>alert(Raw_Album_Info);</script>
The code above does not work unless I include the final "alert" line. It displays a blank message, but it works. If I add a second alert statement it shows the contents of the source file.
At the bottom of the page I have this:
<script language="JavaScript" type="text/javascript">
window.onload = LoadAlbumInfo();
var slideIndex = 2;
showSlides();
</script>
LoadAlbumInfo parses the file and draws content on the page.
Clearly there is an onload-type issue going on here but I can't figure it out. Any suggestions?
Bump on Feb 11. Still looking for a solution.
I tried everything I can think of, from setTimer to moving the code around, to a second window.onLoad statement, and the only thing that gets this to work is inserting an alert statement in the code anywhere between where the script is created and when the script element is used.
If I can't figure this one out I can always resort to putting 8-10 identical html files in different folders, but that would be a pain to maintain, and not pretty.
As for using php etc, this project is going on a thumb drive. It is stand-alone. No server, no Internet.
来源:https://stackoverflow.com/questions/54583628/loading-a-local-file-using-javascript