0

Is it possible to define a varible as the contents of an external text file?

Example:

function getfile() {
        var textfromfile = (contents of http://example.com/plain.txt);
}

Plain.txt is one line and not particlaly long.

Because I am using this for a chrome extension I am not allowed to use php - Is there an easy way to do this in Javascript?

infused
  • 24,000
  • 13
  • 68
  • 78
JBithell
  • 627
  • 2
  • 11
  • 27

1 Answers1

2

You can make an ajax call using jQuery and assign the response to the variable,

  $.ajax({
    url: "plain.txt",
    cache: false
  })
  .done(function( html ) {
    useIt(html);

  });

  //Useful to use variable after callback
  function useIt(variable) {
    alert(variable);
  }
nmos
  • 146
  • 1
  • 8
  • 1
    Important note: this is asynchronous code. You cannot use `variable` right after this code, only inside the `done()` callback. – Xan Jul 27 '14 at 16:44
  • @Xan is there a way to use the var outside the done() callback? – JBithell Jul 27 '14 at 17:23
  • 1
    @JBithell just declare a variable outside the callback I have edited the answer to show you – nmos Jul 27 '14 at 17:32
  • 1
    @JBithell see http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – rsanchez Jul 27 '14 at 17:32
  • @nmos reverted the downvote; to make the answer better, include a short remark on this (why is it important) – Xan Jul 27 '14 at 18:16