I have a text file with a lot of values and I want to know if there is a way of loading these text file values into java script so that these values van be used by the script itself. Note I'm a newbie...
-
1JavaScript running where? (browser? node.js? Windows Scripting Host? etc?)Quentin– Quentin2012-09-02 13:39:48 +00:00Commented Sep 2, 2012 at 13:39
-
Text file where? (user's local file system? the same webserver as the page was loaded from? etc?)Quentin– Quentin2012-09-02 13:40:23 +00:00Commented Sep 2, 2012 at 13:40
4 Answers
You haven't provided much context, but if we assume you mean "JavaScript running in a browser via an HTML page loaded from the same server as the text file", then you want to use the XMLHttpRequest object.
(Which is well documented in many places, so rather then providing yet another tutorial here, I'll let people use Google in the unlikely event of the above link breaking).
There are no shortage of libraries that abstract XHR. e.g. YUI, a host of tiny libraries and jQuery.
2 Comments
Assuming the text file is on your web server and you are loading from the browser, you could use jQuery like so:
jQuery.get('http://localhost/mytextfile.txt', function(data) {
alert(data);
});
2 Comments
Using XMLHttpRequest, you can achieve.
Example:
function ajaxCall() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
xmlhttp = ajaxCall();
xmlhttp.open('GET', 'YOURFILE.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}