Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Js

Idiom #101 Load from HTTP GET request into a string

Make an HTTP request with method GET to the URL u, then store the body of the response in the string s.

const res = await fetch(u)
s = await res.text()

Fetch is a relatively new API and isn't available in IE. A polyfill can be found here: https://github.com/github/fetch

Async/await is also an ES2017 feature.
fetch(u)
  .then(res => res.text())
  .then(text => s = text)

Fetch is a relatively new API and isn't available in IE. A polyfill can be found here: https://github.com/github/fetch
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() { 
	if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
		s = xmlHttp.responseText;
}
xmlHttp.open("GET", u, true);
xmlHttp.send(null);

This is asynchronous.
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
$.get(u, function(data){
  s = data;
});

Uses the jQuery library.
(def s (slurp u))

New implementation...