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

后端 未结 9 714
南笙
南笙 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:20

    XMLHttpRequest, i.e. AJAX, without the XML.

    The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:

    var client = new XMLHttpRequest();
    client.open('GET', '/foo.txt');
    client.onreadystatechange = function() {
      alert(client.responseText);
    }
    client.send();

    Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.

    One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.

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

    Update 2019: Using Fetch:

    fetch('http://localhost/foo.txt')
      .then(response => response.text())
      .then((data) => {
        console.log(data)
      })
    

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

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

    here is how I did it in jquery:

    jQuery.get('http://localhost/foo.txt', function(data) {
        alert(data);
    });
    
    0 讨论(0)
提交回复
热议问题