I'm trying to create a menu from an XML file. The HTML file that I want to create the menu in, is located my main project folder. This folder also contains an xml folder in which my xml file (fruitDB.xml) is located. I understood that there are several ways of loading XML files and that some ways only work online. Eventually the menu is used for an HTML5 mobile app (don't know if this is usefull information), build using Appcelerator.
I've read some sources but it's still not clear to me how I can load an XML file. I have the following code in my header tag:
<script type="text/javascript">
function init(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "xml/fruitDB.xml", false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var Fruits = xmlDoc[];
alert(Fruits);
for (var i = 0; i < Fruits.children.length; i++) {
alert("hi");
var Fruit = Fruits.children[i];
var Name = Fruits.getElementsByTagName("name");
var Thumb = Fruits.getElementsByTagName("image");
var list = document.getElementById("menuButtons");
var listEntry = document.createElement("LI");
listEntry.document.createTextNode(Name);
list.appendChild(listEntry);
}
}
</script>
What I try to do here is open the init(); function using , load the xml file, though I'm not sure if giving a path (like I'm doing) is correct. After the XML is loaded it should create new 's in my HTML file and give them name (and eventually an image) which are stored in the xml file until all items from the xml are placed as list items. Sorry for the long sentence :P.
At xmlhttp.send(); I recieved the following error in my console:
XMLHttpRequest cannot load file:///D:/folder/folder/folder/xml/fruitDB.xml. Received an invalid response. Origin 'null' is therefore not allowed access.
Does this mean that using XMLHttpRequest won't work on local files and if not what other way can I use in order to achieve my goal?
XML doesn't have great support in Titanium. Also XML is often a pain to work with..
Why not use a JSON payload / document instead!
Format the JSON so it is an array of fruit objects
Then you just parse the payload into a javascript object that comes back from the web-service or your local file something like this:
var fruits = JSON.parse(yourHTTPObj.responseData);
Now you can loop over the fruit objects and say:
if (fruits[i].type === 'Apple') { //do something };
Related
I am currently on a Chromebook using HTML, CSS, JS on repl.it, and I can't find a way to check the files in a folder.
I have a folder called objects containing a bunch of JSON files. I want the object dataQueue to hold every object, and I have got that working. But I don't want to have to specifically type out each file to make it run the function I made called getFile for every single file, as is done below in the code.
I am also trying to do this without any libraries (so I can understand everything), and also I want it to be able to run both as a site on the computer and on repl.it.
This is my current code:
//defined the dataQueue object where the object files
//will be stored
var dataQueue={};
//a function to get files by just inputting their
//filename and what i want to call them with in the future
function getFile(theFile,index){
//sets to a new request
var txtFile = new XMLHttpRequest();
//works with any file type, gets the specified file
txtFile.open("GET", theFile, true);
//I don't know what this does
txtFile.send(null);
//runs when the file is recieved
txtFile.onreadystatechange = function(){
//test to make sure it is ready
if(txtFile.readyState==4){
//add object file to dataQueue object
dataQueue[index]=JSON.parse(txtFile.response);
}
}
}
//get each file individually
getFile("objects/ship1.json","ship1");
getFile("objects/box1.json","box1");
getFile("objects/bigplatform1.json","platform1");
getFile("objects/bigbox1.json","bigbox1");
I want to be able to just add another JSON file to the objects folder and have it put in the dataQueue object without needing to add another getFile function.
I think a solution would be if I could somehow get a list of strings containing all of the filenames in the Objects folder, but I have tried finding a way to, and I couldn't find anything.
The question: How do I get each file name in a specific folder in a website's files?
I am working with Angular 5, I have an application in which I need to read an AMP HTML file as text. This file is contained in a component and should only be accessed from this component.
I would like to be able to open the file in read-only by giving its name.
I'm actually searching for something like this:
let file = open('amp.html');
Is it possible? If not how can I do to achieve this?
If you're writing browserside JS
You can't just simply read a file. The JS is running on your browser, and you need to think about where you're getting that file from.
If the file is on a server, you need to fetch that file from the server first by making a request for it.
If you're reading a file on the user's computer, you're gonna be using the File API on the browser to allow the user to select that file.
If you're writing backend JS
Assuming you're using NodeJS, you can conduct file operations like you would with other programming languages. Check out the fs module
If i understand you correct, you can read it as text like this:
function readFile(file){
var raw = new XMLHttpRequest(); // create a request
raw.open("GET", file, false); // open file
raw.onreadystatechange = function (){ // file is ready to read
if(raw.readyState === 4){
if(raw.status === 200 || raw.status == 0){
var allText = raw.responseText;
alert(allText); // can be also console.logged, of course.
}
}
}
raw.send(null); // return control
}
usage:
readFile('link.html')
I solved this issue thankfully to this question.
I'm saving large text files as objects in Parse. They are too large to save directly as text in a normal String column.
Later, I want to retrieve these files and process the text in JavaScript.
Here's the code I'm using to store the text in a Parse file:
// Inputs
var long_text_string = '...'; // A long string
var description = '...'; // Description of this string
// Convert string to array of bytes
var long_text_string_bytes = [];
for (var i = 0; i < long_text_string.length; i++) {
long_text_string_bytes.push(long_text_string.charCodeAt(i));
}
// Create Parse file
var parsefile = new Parse.File("long_text_string.txt", long_text_string_bytes);
parsefile.save({
success: function() {
// Associate file with a new object...
var textFileObject = new Parse.Object("TextFile");
textFileObject.set('description', description);
textFileObject.set('file', parsefile);
textFileObject.save();
}
});
How do I then retrieve the content of the data file, convert it back from bytes to string, and end up with it stored in a normal string variable in JavaScript?
UPDATE
I've tried three different approaches, all to no avail...
Method 1 [preferred]
Use Parse commands to process the file
It's simple to use the Parse JS API to retrieve my TextFile object, and use parseFile = object.get('file'); to get the Parse file itself. The URL of the file is then parseFile.url().
But then what? I can't do anything with that URL in JS because of cross-origin restrictions.
There is no documentation on how to use the JS API to access the byte data contained within the file. There appears to be an Android command, getDataInBackground, documented here, so I am hopeful there is a JS equivalent....
Method 2
Use the Parse REST API to fire a XMLHTTP request
Unfortunately, it seems that Parse have not enabled CORS for their file URLs. I have tried the following code, adapted from a Parse.com blog post (blog.parse.com/learn/engineering/javascript-and-user-authentication-for-the-rest-api/):
var fileURL = textFileObject.get('file').url();
var xhr = new XMLHttpRequest();
xhr.open("GET", fileURL, true);
xhr.setRequestHeader("X-Parse-Application-Id", appId);
xhr.setRequestHeader("X-Parse-REST-API-Key", restKey);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
};
var data = JSON.stringify({ message: "" });
xhr.send(data);
But I get the following error:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin '<my host>' is therefore not allowed access.
The response had HTTP status code 403
A bit of a Google suggests that the file URLs are not CORS-enabled (parse.com/questions/access-control-allow-origin--2).
(Note that the above code works for a normal object request, it's only when you use the fileURL that it errors).
Method 3
Use a browser to circumvent cross-origin restrictions
I can create a webpage with an empty iframe and set iframe.src to parseFile.url(). The content of the file appears on the web page. But I still end up with cross-origin issues when I try to access the DOM content of the iframe! Not to mention loading each file onto a webpage one by one is an incredibly substandard solution.
I'm currently working on a small project in which I want to convert couple (or more) Markdown files into HTML and then append them to the main document. I want all this to take place client-side. I have chose couple of plugins such as Showdown (Markdown to HTML converter), jQuery (overall DOM manipulation), and Underscore (for simple templating if necessary). I'm stuck where I can't seem to convert a file into HTML (into a string which has HTML in it).
Converting Markdown into HTML is simple enough:
var converter = new Showdown.converter();
converter.makeHtml('#hello markdown!');
I'm not sure how to fetch (download) a file into the code (string?).
How do I fetch a file from a URL (that URL is a Markdown file), pass it through Showdown and then get a HTML string? I'm only using JavaScript by the way.
You can get an external file and parse it to a string with ajax. The jQuery way is cleaner, but a vanilla JS version might look something like this:
var mdFile = new XMLHttpRequest();
mdFile.open("GET", "http://mypath/myFile.md", true);
mdFile.onreadystatechange = function(){
// Makes sure the document exists and is ready to parse.
if (mdFile.readyState === 4 && mdFile.status === 200)
{
var mdText = mdFile.responseText;
var converter = new showdown.Converter();
converter.makeHtml(mdText);
//Do whatever you want to do with the HTML text
}
}
jQuery Method:
$.ajax({
url: "info.md",
context: document.body,
success: function(mdText){
//where text will be the text returned by the ajax call
var converter = new showdown.Converter();
var htmlText = converter.makeHtml(mdText);
$(".outputDiv").append(htmlText); //append this to a div with class outputDiv
}
});
Note: This assumes the files you want to parse are on your own server. If the files are on the client (IE user files) you'll need to take a different approach
Update
The above methods will work if the files you want are on the same server as you. If they are NOT then you will have to look into CORS if you control the remote server, and a server side solution if you do not. This question provides some relevant background on cross-domain requests.
Once you have the HTML string, you can append to the whatever DOM element you wish, by simply calling:
var myElement = document.getElementById('myElement');
myElement.innerHTML += markdownHTML;
...where markdownHTML is the html gotten back from makeHTML.
I am building a javascript component for Firefox that will take in a zip code, and will return the current weather conditions.
The sample code that weather underground uses jQuery, but as I understand it, I cannot include this code in my javascript component, as javascript does not have the functionality to include other javascript files.
At any rate, I have built up my skeleton code. It takes in the zip code and builds up the url
(example: http://api.wunderground.com/api/e17115d7e24a448e/geolookup/conditions/q/22203.json)
I have tried downloading the data from that url, via the following method:
getWeatherByUrl: function(url)
{
var persist = Components.classes["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
var file = Components.classes["#mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD",Components.interfaces.nsILocalFile);
file.append("weather-forecaster.dat");
var urlURI = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(url, null, null);
persist.saveURI(urlURI,null,null,null,"",file);
return url;
}
This should download the file to the user's profile directory. It indeed does create the file there. However, it does not look like it contains the json data from weather underground.
What exactly is going on? How would I download the file? I believe that there is a query going on when that url is passed to weather underground, but that shouldn't matter as the .json page is what gets spit out from them, right?
Is there a way to do this without downloading the file, but by streaming it and parsing it?
You can simply use XMLHttpRequest to download this data:
var request = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
request.open("GET", "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json");
request.addEventListener("load", function(event)
{
var data = JSON.parse(request.responseText);
alert(data.response.version);
}, false);
request.send(null);