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?

1
  • You need to use async Ajax. If you want simplicity I would recommend using jQuery it has a nice load function. api.jquery.com/load Commented Sep 12, 2017 at 20:53

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

this doesn't works getting an error at last line xhr.send(null)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.