Skip to content Skip to sidebar Skip to footer

Loading A Text File Into Javascript

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 itsel

Solution 1:

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.

Solution 2:

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);
});

Solution 3:

Using XMLHttpRequest, you can achieve.

Example:

functionajaxCall() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = newXMLHttpRequest();
    }
    elseif (window.ActiveXObject) {
        // code for IE6, IE5
        xmlhttp = newActiveXObject("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);
    }
}

Solution 4:

with jQuery:

$('#result').load('ajax/test.txt');

Html code:

<div id="result">Text loaded here</div>

After loading the text will be replaced with the text file.

Post a Comment for "Loading A Text File Into Javascript"