How can I load the contents of a small text file into a javascript var wo/JQuery?

2.6k Views Asked by At

I'm trying to load a very simple text file (eg: 0 online: or 1 online: Username or 2 online: Username, Username), from a server I control, that changes based on the number of users on a minecraft server, into a javascript var, so that I can eventually load it onto my Pebble and have it more or less live update. (read: no jquery) (also read: I have little to no idea what I'm actually doing, and if there's a better way to do it, lemme know.).

I've done a lot of googling which mostly points me to using JSON and XMLHTTPRequests (edit: XMLHTTPRequests are probably necessary) but they seem overly complex for what I need (which is to take the contents of the text file served up via HTTP, stuff it in a var, and have the Pebble spit it out on the screen.)

How can I, without JQuery, and maybe even without JSON, load the contents of a text file into a javascript var?

Some notes:

  • The server is eventually going to be accessed via Hamachi, but if I can get it working even locally I'll be pretty thrilled.
  • Following this answer, I get this result. Ditto for local IP.
2

There are 2 best solutions below

1
On BEST ANSWER

This is very easy to do, just include this wrapper for the XmlHttpRequest at the beginning of your script (it makes it easier to use):

var xhrRequest = function (url, type, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function () {
    callback(this.responseText);
  };
  xhr.open(type, url);
  xhr.send();
};

And then call it like this:

xhrRequest(url, 'GET', function(responseText) { 
  console.log("This is the content you got: " + responseText);
});

If you format your content in JSON it will actually make things easier for you because you will not have to parse the file and you can use JavaScript to parse it for you automatically:

For example if the reply is:

{ onlineCount: 42, usernames: [ "Alice", "Bob", "Charlie", "etc" ] }

Then you can process it like this:

xhrRequest(url, 'GET', 
  function(responseText) {
    // responseText contains a JSON object
    var json = JSON.parse(responseText);

    // Now you can process this as a JavaScript dictionary
    console.log("Number of online players: " + json.onlineCount);
    console.log("First player: " + json.usernames[0]);

    // And send messages to Pebble
    Pebble.sendAppMessage({ 0: json.onlineCount });
  }
);

For a complete example and the C side (on Pebble), you should take a loot at Step 3 of the Pebble Tutorial, it does exactly this with weather data.

3
On

The simplest approach would be to format the text file as a js file:

var playerinfo = "1 online: Username";

and include the script like a usual js:

<script type="text/javascript" src="http://localhost/mytextfile.js"></script>

Then the page would have a variable playerinfo for your js code to use.