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

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

提交回复
热议问题