从 url 中的 txt 文件中获取文本 [英] Get text from a txt file in the url

查看:71
本文介绍了从 url 中的 txt 文件中获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我转到这样的网址时:http://my.url.com/file.txt,浏览器会显示文本.

When I go to a url like this: http ://my.url.com/file.txt, the browser shows text.

我想要一个执行以下操作的简单 javscript 命令:
1.转到网址
3. 取屏幕上显示的文字
4. 将其存储在变量中以供进一步处理

I would like a simple javscript command that does the following:
1. go to the url
3. take the text that shows up on the screen
4. store it in a variable for further processing

有点像

var url = http: //my.url.com/file.txt;

//这里的一些代码去url

//some code here that goes to the url

//一些获取所述信息并执行以下操作的代码:

//some code that takes said info and does something like:

var fileInfo = ---content of file.txt---

请注意,我从 txt 文件中查找的信息在 html 标签中

Note that the info I seek from the txt file is in html tags

<p>Text I need in Variable</p>

如有任何帮助,我们将不胜感激!
谢谢!

Any assistance would be greatly appreciated!
Thank you!

推荐答案

使用 Fetch API.

一起玩 jsfiddle.net.

var url = 'https://fiddle.jshell.net/robots.txt';
var storedText;

fetch(url)
  .then(function(response) {
    response.text().then(function(text) {
      storedText = text;
      done();
    });
  });

function done() {
  document.getElementById('log').textContent =
    "Here's what I got! \n" + storedText;
}

这是一个较小的 ES6 示例,它将获取与存储和展示结果分开.

Here's a smaller ES6 example that separates fetching from storing and showing off the result.

fetch('https://fiddle.jshell.net/robots.txt')
  .then((response) => response.text().then(yourCallback));

function yourCallback( retrievedText ) { /* . . . */ }

已经全面采用.

您不必等待.大多数人不会.你不应该.
GitHub 提供了无法升级的 polyfill.

You don't have to wait. Most people don't. You shouldn't.
GitHub provides a polyfill of those who can't upgrade.

fetch 有什么比 XHR 更好的地方?... 大量.

What's better about fetch than XHR? ... Lots.

这篇关于从 url 中的 txt 文件中获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆