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

后端 未结 9 706
南笙
南笙 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: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!
    `;
    
    

    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.

提交回复
热议问题