0

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...

Alex
  • 25,147
  • 6
  • 59
  • 55
user481610
  • 3,230
  • 4
  • 54
  • 101

4 Answers4

0

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Sorry for the lack of info. Here's the story. I'm using Google maps to draw polygons on the map. To do this I need to using A LOT of latitude and Longitude points, but I dont want this in my javascript code, I want to import the Coordinates and then use those coordinates in the javascript. I'm very keen to learn so just point me in the right direction and I'll go read up – user481610 Sep 02 '12 at 13:58
  • XHR is probably the right choice then, but you should format the data as [JSON](http://json.org) rather then your own custom text format. – Quentin Sep 02 '12 at 14:40
0

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);
});
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

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);
    }
}
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
0

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.

Codebeat
  • 6,501
  • 6
  • 57
  • 99