1

I am writing my own library and i have a text file which i need to load into a variable. I know i can do this using Jquery but i would really like to know how this is done using java script native. I couldn't find any good resources for this so here i am :/

Soooo how do i replace this code with javascript?

$('#result').load('txt.txt', function() {
  alert('Load was performed.');
});

I actually need the text to be in a variable and not an element.

THE AMAZING
  • 1,496
  • 2
  • 16
  • 38
  • im not sure but i found a nice link here http://stackoverflow.com/questions/196498/how-do-i-load-the-contents-of-a-text-file-into-a-javascript-variable is this the solution i am looking for? – THE AMAZING Aug 26 '13 at 02:39
  • 1
    jQuery _is_ Javascript. Look up AJAX on MDN. – SLaks Aug 26 '13 at 02:42

1 Answers1

1

Very simplified it would look like this:

var oReq = new XMLHttpRequest();

oReq.open("GET", 'txt.txt', true);
oReq.onload = function(e) {
  var myText = oReq.responseText; 
  /* ... */
}
oReq.send();

There is much more to it though, as you need to account for network timeouts, possibility that the NIC is not available (WiFI is down, e.g.), server errors etc. jQuery does help to take care of this stuff.

One resource to check out for more is this: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Update:

Fiddle example: http://jsfiddle.net/Exceeder/epGFH/ Also note, that this solution is not compatible with IE 6, as XHR was introduced into IE only after W3C standardization, i.e. in IE 7.

Alex Pakka
  • 9,466
  • 3
  • 45
  • 69