user3502985
user3502985

Reputation: 21

Javascript code to read a.txt file

I need a JavaScript code to read in a dictionary stored as a .txt file (or can be saved as any other type of file as well. It is also available online) and store its contents in a variable.I could not find a way for JavaScript to read in files like Java does. I discovered it can be easily accomplished using PHP. However I am unable to pass the contents of the dictionary stored as a variable in PHP to JavaScript. Can help me accomplish this, either only using JavaScript or using both JavaScript and PHP

Upvotes: 2

Views: 97

Answers (1)

user3233318
user3233318

Reputation:

You can use AJAX to load that file. Here is an example:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style></style>
    <script>
      window.addEventListener("load", function(){
        var request = new XMLHttpRequest()
        request.onreadystatechange = function(){
          if(request.readyState == 4 && request.status == 200){
            console.log(request.responseText)
          }
        }
        request.open("GET", "txt.txt", true)
        request.send()
      })
    </script>
  </head>
  <body>
  </body>
</html>

Upvotes: 2

Related Questions