Last active
September 4, 2017 16:15
-
-
Save abrahamjuliot/8cb3fe31eb50cde85e58597a82188acb to your computer and use it in GitHub Desktop.
mini xhr library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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