Reputation: 109
I have created a bunch of local HTML files and I'm trying to translate them thanks to xml files and a lot of JavaScript/JQuery. The translation part is done and I'm now trying to do a pulldown menu with all of the xml files to select the desired language.
First, I tried to scan a local folder named "images" and print the name of my files in a blank html page but I was not able to do it. I did a lot of research on stack overflow and on forum.jquery.com but even if I tried a lot of things, nothing worked.
Here is what I pulled of for the moment :
HTML side :
<body>
<div id="fileNames">
<p></p>
</div>
<script>window.onload=ChangeLangue</script>
</body>
JS/Jquery side :
var folder = "images/";
$.ajax({
url: folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|png|gif)$/)) {
$("body").append("<img src='" + folder + val + "'>");
}
});
}
});
What am I doing wrong? Is this possible?
Upvotes: 2
Views: 4017
Reputation: 8761
Browsers don't allow cross origin requests. An error will be thrown as
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Because the protocol is file://
You can do it by setting a flag:
Quit Chrome.
Restart using following command.
MAC : In terminal, open /Applications/Google\ Chrome.app --args --allow-file-access-from-files
WINDOWS : In Run, C:/PATH_TO_CHROME_INSTALLATION_FOLDER/chrome.exe --allow-file-access-from-files
Now you can access the files from your computer. To verify it, you can go to chrome://version
and you can see the flag
enabled under the Command Line
section.
As you have var folder="images/"
, and suppose the page loaded in the browser is in /Users/Default/Desktop
folder, the ajax request made will be
file:///Users/Default/Desktop/images
If you add /
before the folder var folder = "/images/"
,
the request will be file:///images/
.
Make sure to provide the required/complete path.
After getting the response, since the response is in html format, you can use document.write(response)
. From there you can view and navigate in/out of folders.
I tried with below JS Code and got the result.
<script type="application/javascript">
var url = "/Users/Default/Downloads";
var req = new XMLHttpRequest();
req.open("GET",url,true);
req.onreadystatechange=function(){
if(req.readyState === 4)
{
document.write(req.responseText);
}
};
req.send();
</script>
P.S. : No idea if it works in Windows machines. Correct me if I am wrong. TIA.
Upvotes: 2