How do I load the contents of a text file into a javascript variable?

后端 未结 9 704
南笙
南笙 2020-11-22 07:22

I have a text file in the root of my web app http://localhost/foo.txt and I\'d like to load it into a variable in javascript.. in groovy I would do this:

         


        
相关标签:
9条回答
  • 2020-11-22 08:00

    Update 2020: Using Fetch with async/await

    const response = await fetch('http://localhost/foo.txt');
    const data = await response.text();
    console.log(data);
    

    Note that await can only be used in an async function. A longer example might be

    async function loadFileAndPrintToConsole(url) {
      try {
        const response = await fetch(url);
        const data = await response.text();
        console.log(data);
      } catch (err) {
        console.error(err);
      }
    }
    
    loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');

    0 讨论(0)
  • 2020-11-22 08:11

    If your input was structured as XML, you could use the importXML function. (More info here at quirksmode).

    If it isn't XML, and there isn't an equivalent function for importing plain text, then you could open it in a hidden iframe and then read the contents from there.

    0 讨论(0)
  • 2020-11-22 08:13

    If you only want a constant string from the text file, you could include it as JavaScript:

    // This becomes the content of your foo.txt file
    let text = `
    My test text goes here!
    `;
    <script src="foo.txt"></script>
    <script>
      console.log(text);
    </script>

    The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a template literal, allowing for both " and ' characters in your text block.

    This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the file:// scheme.

    0 讨论(0)
  • 2020-11-22 08:13

    One thing to keep in mind is that Javascript runs on the client, and not on the server. You can't really "load a file" from the server in Javascript. What happens is that Javascript sends a request to the server, and the server sends back the contents of the requested file. How does Javascript receive the contents? That's what the callback function is for. In Edward's case, that is

        client.onreadystatechange = function() {
    

    and in danb's case, it is

     function(data) {
    

    This function is called whenever the data happen to arrive. The jQuery version implicitly uses Ajax, it just makes the coding easier by encapsulating that code in the library.

    0 讨论(0)
  • 2020-11-22 08:16

    When working with jQuery, instead of using jQuery.get, e.g.

    jQuery.get("foo.txt", undefined, function(data) {
        alert(data);
    }, "html").done(function() {
        alert("second success");
    }).fail(function(jqXHR, textStatus) {
        alert(textStatus);
    }).always(function() {
        alert("finished");
    });
    

    you could use .load which gives you a much more condensed form:

    $("#myelement").load("foo.txt");
    

    .load gives you also the option to load partial pages which can come in handy, see api.jquery.com/load/.

    0 讨论(0)
  • 2020-11-22 08:18

    This should work in almost all browsers:

    var xhr=new XMLHttpRequest();
    xhr.open("GET","https://12Me21.github.io/test.txt");
    xhr.onload=function(){
        console.log(xhr.responseText);
    }
    xhr.send();
    

    Additionally, there's the new Fetch API:

    fetch("https://12Me21.github.io/test.txt")
    .then( response => response.text() )
    .then( text => console.log(text) )
    
    0 讨论(0)
提交回复
热议问题