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

后端 未结 9 892
南笙
南笙 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.

提交回复
热议问题