17

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

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

so something like

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

//some code here that goes to the url

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

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

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!

4

4 Answers 4

15

Use the Fetch API.

Play with it at 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;
}

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 ) { /* . . . */ }

Adoption is already across the board.

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

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

Sign up to request clarification or add additional context in comments.

5 Comments

Disclaimer: Fetch support is at a fairly early stage, but progress is being made. It is turned on by default in Firefox 39 and above, and Chrome 42 and above.
For older browsers or people that refuse to update; github.github.io/fetch
Thank you very much for your response, but this is the error I am getting when running this in a blank console: Fetch API cannot load http:// www.my-sample-url.com/file.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome://newtab' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. undefined:1 Uncaught (in promise) TypeError: Failed to fetch(…)
You're fetching from a modification to chrome://newtab? And you're trying to fetch an external resource... Hm. Try creating a Request instead of using the URL as a string parameter to fetch. Specify the .mode as 'no-cors'. In this state, it may not be possible to retrieve the text. You may need to ask this as a different question concerning chrome://newtab specifically.
Excellent example. I just made a bare-bones static site handler (didn't want all the overhead of a 'real' SSG) that pulls in .md files using fetch and converts them to HTML inside my static HTML pages on the fly. Now I can just git push and the site is updated on GitHub pages :-)
6

Make an AJAX call to the url. Here is using the jQuery library:

$.get( "http: //my.url.com/file.txt", function( data ) {
  var text = data;
});

To extract what you need from your text string in between the paragraph tags, try regex:

var pText = text.match(/<p>([^<]+)<\/p>/)[1];

7 Comments

You makes assumptions: everyone use JQuery ?!
You really want to use vanilla javascript? stackoverflow.com/questions/8567114/…
There's some cases where you're stuck with vanilla JS ;)
@ndcomix +1 for sassiness
If you're a CasperJS dev, you play with what the remote website use. If there's no JQuery, no cigar. It's an example
|
0

Using vanilla JS :

From the MDN doc :

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Read the doc and ndcomix SO link to go further (error checking and such)

2 Comments

Since before Febuary of 2015, we've been climbing out of the dark ages. davidwalsh.name/fetch gauntface.com/blog/2015/02/11/fetch-is-the-new-xhr
Disclaimer: Not supported in all browsers. Here's a polyfill. github.com/LuvDaSun/xhr-polyfill
-2

Just use jquery. It's easy fun and extensible. Don't try bizzare uses. Be sure all the time to be compatible through all the browser. If you copy this and run it under a local or remote webserver will work like a charm. Cheers.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({url: "test.txt", success: function(result){
            $("#div1").html(result);
        }});
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.