Skip to content

Instantly share code, notes, and snippets.

@abrahamjuliot
Last active September 4, 2017 16:15
Show Gist options
  • Save abrahamjuliot/8cb3fe31eb50cde85e58597a82188acb to your computer and use it in GitHub Desktop.
Save abrahamjuliot/8cb3fe31eb50cde85e58597a82188acb to your computer and use it in GitHub Desktop.
mini xhr library
// factory
const http = () => {
const
XHR = () => {
return new XMLHttpRequest()
},
onload = (req, fn, parse = true) => {
req.onload = () => {
if (req.status >= 200 && req.status < 400) {
let data = req.responseText
;(parse) && (data = JSON.parse(data))
fn(data) // execute callback with data
}
}
}
return {
post (url) {
const req = XHR()
req.open('POST', url, true)
req.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'
);
request.send(data)
},
get (url, fn, parse) {
const req = XHR()
req.open('GET', url, true)
onload(req, fn, parse)
req.send()
}
}
}
// app
const
xhr = http(),
url = 'https://teamtreehouse.com/abrahamjuliot.json'
console.time("Response Time")
xhr.get(url, (data) => {
console.log(`${data.name} has ${data.points.total} points`)
console.timeEnd("Response Time")
});
console.log('do something else while I\'m waiting')
//test at https://repl.it/FJhN/25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment