1

I'm surprised to see that this is hard to do, but i haven't found a single way to do that. Basically i have a directory that contains:

--index.html
--script.js
--file.xml

And i want to read the content of the file.xml to a JS string for parsing. The only method i found of doing so was by using a synchronous xmlhttp object which is disabled by default in my browser. Is there another (preferably easy) way of reading a file to a string in js?

Keitio
  • 13
  • 1
  • 6
  • You need to use async Ajax. If you want simplicity I would recommend using jQuery it has a nice load function. http://api.jquery.com/load/ – Thomas Devries Sep 12 '17 at 20:53

1 Answers1

0

So, I might be a little late to the party, but this is to help anybody else who's been ripping his/her hair out looking for a solution to this.

First of all, CORS needs to be allowed in the browser if you're not running your HTML file off a server. Second, I found that the code snippets most people refer to in these kind of threads don't work for loading local XML-files. Try this (example taken from the official docs):

var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', true);

xhr.timeout = 2000; // time in milliseconds

xhr.onload = function () {
  // Request finished. Do processing here.
  var xmlDoc = this.responseXML; // <- Here's your XML file
};

xhr.ontimeout = function (e) {
  // XMLHttpRequest timed out. Do something here.
};

xhr.send(null);

The method (1st arg) is ignored in xhr.open if you're referring to a local file, and async (3rd arg) is true by default, so you really just need to point to your file and then parse the result! =)

Good luck!

adamxtokyo
  • 21
  • 4