Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Using JavaScript/JQuery to get words from a text file

  1. May 5, 2014 #1
    I was searching around the internet for a procedure to read lines of a text file into a JavaScript array. Most of the procedures I saw used Ajax, which I don't understand yet, so I'll refrain from trying to cut-and-paste code that I don't understand.

    I found this

    Code (Text):

            $.get('wordsEn.txt', function(myContentFile)
                words = myContentFile.split("\r\n");
            }, 'text');
    JQuery function call, which does the trick, but how can I get words into the scope outside of the function call? I want to actually be able to use it.
  2. jcsd
  3. May 5, 2014 #2
  4. May 5, 2014 #3
    You can declare "var words" before the .get call - but I think that's only half the problem.
    I haven't used jQuery, but I suspect that "myContentFile" becomes available asynchronously to the rest of the program. So let's say you put the "var words;" and "$.get(..." in the <head> section and a reference to the words array "later" in the body. What will happen is that the reference in the body will happen before the data is ready - that is, before the "function(myContentFile)" is called.

    Unless you're already using the jQuery library, I would used code such as this:
    Code (Text):
    <script type="text/javascript">
    var Words;
    var WordFile = new XMLHttpRequest();
      WordFile.open("GET", "file:///C:/temp/html/words.txt", false);
      WordFile.onreadystatechange =
        function () {
          if(WordFile.readyState === 4)
            if(WordFile.status === 200 || WordFile.status == 0)
              Words = WordFile.responseText.split("\r\n");
    <script type="text/javascript">
  5. May 8, 2014 #4
    Seems to work. Thanks.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook