0

I have seen several examples of how to load a file with javascript, however most of those examples use the data from the file to display it in a html.

I need to keep accessing a file since the file keeps updating and use those values in javascript as variables.

I got the closest with this,

function test() {

    $().ready(function(){ 
        var url = 'output.txt';
        $.get(url, function(data) {
            // can use 'data' in here...
            console.log(data);
        });
    });
}

It logs document to the console and I can collapse that.

There is really a lot of stuff (to much to list here). I only don't know in what kind of format it needs the data to be or how to access it. I do see stuff about xml-stylesheet, so can i even use this?

Changing the way I write the file is no problem for me.

2
  • 1
    Have you tried JSON? Commented Dec 29, 2011 at 19:54
  • json would be the easiest to parse, as the file keeps changing would wrapping the $.get... in a loop work? Commented Dec 29, 2011 at 20:19

2 Answers 2

3

I suggest using a JSON file. For example:

{
  username: "Rocket",
  realname: "Eric",
  age: 23
}

To read this, you can use jQuery's $.getJSON method.

$.getJSON('/path/to/your/file.json', function(data){
    var username = data.username;
});

You can also use XML, though I suggest using JSON (it's easier to get the data from it).

<?xml version="1.0" encoding="UTF-8" ?>
<item> <!-- XML needs a root element -->
  <username>Rocket</username>
  <realname>Eric</realname>
  <age>23</age>
</item>

jQuery doesn't have a $.getXML method, so we have to use $.get.

$.get('/path/to/your/file.xml', function(data){
    var username =  $('item', data).find('username').text();
}, 'xml');
Sign up to request clarification or add additional context in comments.

Comments

0

Try using the Jquery GetJson method: Something like this. May need some tweaking.

$.ajax({
  url: 'http://www.yourfile.html',
  dataType: 'json',
  data: data,
  success: function(data){

  $('#yourdiv').html(data);

  }
});

1 Comment

Setting the HTML to the JSON data isn't going to do anything useful. Depending on the JSON, you'd want something like data.html or whatever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.