简体   繁体   中英

How do I read txt file from url with javaScript?

I have followed the instruction on this page but I'm unable to solve the problem.

Here's my code: When file link is clicked it downloads the f.txt file. But I want to access the data without downloading through the url.

var file = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=hi&dt=t&dt=t&q=hello';
      function readTextFile(file) {
          var rawFile = new XMLHttpRequest();
          rawFile.open("GET",file,false);
          rawFile.onreadystatechange = function() {
              if(rawFile.readyState === 4) {
                  if(rawFile.status === 200 || rawFile.status === 0)
                  {
                      var allText = rawFile.responseText;
                      alert(allText);
                  }
              }
          }
          rawFile.send(null);
      }
  <body>
      <a id="myLink" href="https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=hi&dt=t&dt=t&q=hello"  ">file link</a>
  </body>

 <script>
     document.querySelector("#myLink").addEventListener("click", function(event){ 
        event.preventDefault(); 
        var file = document.getElementById("myLink").getAttribute("href");
        console.log(file)
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET",file,false);
          rawFile.onreadystatechange = function() {
              if(rawFile.readyState === 4) {
                  if(rawFile.status === 200 || rawFile.status === 0)
                  {
                      var allText = rawFile.responseText;
                      console.log(allText);
                  }
              }
          }
          rawFile.send(null);
    }, false); 

  </script>

This approach will get you the read the content of the file.. This way will be helps to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM