2017-03-17 273 views
0

我按照这个page的说明,但我无法解决问题。如何使用javaScript从url中读取txt文件?

这里是我的代码: 当点击file link它下载f.txt文件。但我想访问的数据,而无需通过网址下载。

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); 
     } 
+0

请尝试关注此链接。 [如何使用JavaScript读取/从URL获取数据](http://stackoverflow.com/questions/814613/how-to-read-get-data-from-a-url-using-javascript) – pd1

+0

你必须改变您可以启动您的javascript fumction或绑定click事件。删除了您当前拥有的服务的网址。 –

+0

@ pd1该网址为我提供了关于如何从网址中提取文本的说明,但我希望在网址加载时从网址获取数据。 点击此网址:https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=hi&dt=t&dt=t&q=hello下载f.txt文件。所以我想访问最终数据。 需要帮助的部分 –

回答

0
<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> 

这种做法将让你在阅读文件的内容。这方法将帮助你。

+0

谢谢@Senthil库马尔的答案。 –