I have seen similar questions here but I just can't understand them.
I am building a small web page and I want to read a .json file from my file system and get the object in it.
The web page is also local and the .json file is in the same folder as the .html file.
How to do that on my Ubuntu machine without using any servers and without jquery if it is possible?
Here's some vanilla javascript XMLHTTPRequest code, which does take into account the IE quirks of ActiveX objects:
var useActiveX = typeof ActiveXObject !== 'undefined';
function loadJSON(file, callback) {
var xobj;
if (useActiveX) {
xobj = new ActiveXObject('Microsoft.XMLHTTP');
} else {
xobj = new XMLHttpRequest();
}
xobj.callback = callback;
if (xobj.overrideMimeType) {
xobj.overrideMimeType('application/json');
}
xobj.open('GET', file, false);
xobj.onreadystatechange = function() {
if (this.readyState === 4) {
this.callback(this);
}
}
xobj.send(null);
}
Then you just run it by feeding it a filepath and a callback function:
loadJSON('filename.json', function(obj) {
alert(obj.responseText);
}
You can simply append a <script> tag to your page, pointing the SRC to the local .js file in the same folder. You don't need to use Ajax.
Related
I'm just trying on the task, file manipulation system using java script. As I was referred from W3C File API( https://www.w3.org/TR/FileAPI/ ), we can only read local files like
var file = "test.txt";
function readTextFile(file) {
var readFile;
if(window.XMLHttpRequest){
// for new browsers
readFile = new XMLHttpRequest();
}else{
//for old browsers like IE5 or IE6
readFile = new ActiveXObject("Microsoft.XMLHTTP");
}
readFile.open("GET", file, true);
readFile.onreadystatechange = function() {
if(readFile.readyState === 4) {
if(readFile.status === 200 || readFile.status == 0) {
//text will be displayed that read from the file
console.log(readFile.responseText);
}
}
}
readFile.send(null);
}
but it looks there is no options to write on file without server. I was tried to fetch solutions from the websites like http://www.stackoverflow.com/, the study says almost there is no possibilities.
For an example what I got is
from https://gist.github.com/Arahnoid/9925725
It shows error "TypeError: file.open is not a function."
So my question is, Is there any possible to file manipulations(asking only about Write file) for local files without using server-side scripting or is any extensions like available?
We can do file manipulations using server scripting languages such as PHP, Node.js.
Thanks in advance.
In your code, it's not reading from the local file (test.txt), it's sending Ajax GET request to server and read file in server side.
To read local file (files that stored in machine where browser is installed), you need to use FileAPI, which is not used in current code.
To write file to local, it's impossible to write it directly using JavaScript. Otherwise, it would be a huge security vulnerability. However, you can generate a URL from File object, and use that URL as the href attribute of <a> tag, so that user can download and "write to local" manually.
Here is a code snippet to read & "write" local file:
var inputElement = document.getElementById("input");
var reader = new FileReader();
var downloadLink = document.getElementById('downloadLink');
reader.onloadend = function(){
console.log(reader.result);
}
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var fileSelected = this.files[0]; /* now you can work with the file list */
reader.readAsBinaryString(fileSelected);
downloadLink.href = window.URL.createObjectURL(fileSelected);
}
<input type="file" id="input">
<a id="downloadLink" download>Download</a>
I have a standard folder structure for a web app.
css
js
img
asetts
lib
index.html
Inside my assets folder I have a bunch of plain text files and I would like to first be able to list the filenames using Javascript, so I can store the URI's in the model, and read from them later on the in the application. I want all of this happening client side.
(Client-side) JavaScript does not have access to the file system like that.
This is not possible without some kind of browser plugin.
You can read the textfiles in the local folder.
function read()
{
var xHR = new XMLHttpRequest();
//replace textfile_url with the relative url of your text file
xHR.open("GET", "textfile_url", true);
xHR.onreadystatechange = function ()
{
if(xHR.readyState === 4)
{
//all your text is in the next line
var text = xHR.responseText;
}
}
xHR.send();
}
My JavaScript has an function that goes off onload that takes a .txt file and creates an array from it. The page works fine in Chrome, but doesn't update in IE -- IE seems to cache the .txt file and re-create the array from the cache, ignoring any updates made to the .txt. Is there any way to force IE to re-download the .txt before creating the array so that the user isn't working with an outdated version of the information?
edit: Code!! (changed the file pathname, all else is the same)
function createArray() {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://PATHNAME/names.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200 || txtFile.status === 0) {
nameArray = txtFile.responseText.split("\n");
}
}
};
txtFile.send(null);
}
Furthermore, the file is stored on the server, in the same folder as the page that the data displays on, which is one level above the JavaScripts folder. So the directories look like:
page.html
names.txt
SCRIPTS FOLDER
array.js
Get requests cache, force it to fetch a new file by changing the url.
txtFile.open("GET", "http://PATHNAME/names.txt?ts=" + new Date().getTime(), true);
I have a code which I used to load external files into a html. How can I do it without importing external files or any libraries, so inside html I can type a short script and it will load another page?
i use this script so far:
$(document).ready(function(){
$('#outer').load('html_file.html');
});
but it requires to have additional files + libraries. How can I do everything directly in html?
Any ideas?
basically I want to include the whole another website inside the new one, but I can use only html + javascript inside the html file. All css files will be stored and reffered in the imported file.
Use this "html":
<script type="text/javascript">
window.onload = function() {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("GET", "html_file.html", false);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
document.getElementById("outer").innerHTML = xhr.responseText;
}
};
xhr.send(null);
};
</script>
there is many examples of reading local files using html5 but by choosing from list of files , my problem is that i want to create the file object manually , think about i have a file with the link
file:///G:/Users/txt.txt
i want the browser to open it ,
i think it have to File f=new File('file:///G:/Users/txt.txt');
my question is how to create/initialize the file object using file path ?!
I have used below workaround since File inherits blob interface.
var getFileBlob = function (url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.addEventListener('load', function() {
cb(xhr.response);
});
xhr.send();
};
var blobToFile = function (blob, name) {
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};
var getFileObject = function(filePathOrUrl, cb) {
getFileBlob(filePathOrUrl, function (blob) {
cb(blobToFile(blob, 'test.jpg'));
});
};
getFileObject('img/test.jpg', function (fileObject) {
console.log(fileObject);
});
There really is no way to create a file without permission from the user. A button or something will need to be pressed. You would need to create a data:uri in order for it to save. You can find more information using a web search or checking out http://en.wikipedia.org/wiki/Data_URI_scheme (not a complete source but can show what is possible). This is very limited depending on phone and OS. Data URI are limited while using IE.
When it is triggered for download, it saves to t he default location or user specified. You may also want to look into vendor/OS specific API Calls that can do as you are describing. But may need to verify permissions prior to actually allowing access.