getJSON in Vanilla JS
As someone who has been using jQuery on and off for over 10 years(!!) now, I have mixed emotions about it. It’s fantastic for loads of use cases, not to mention cross browser compatibility.
However, I’ve found myself in a handful of situations where all I need is $.getJSON
and I’m less worried about older browsers. So I cobbled together this gist:
This file contains 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
/* | |
* Usage: | |
* getJSON("https://jsonplaceholder.typicode.com/comments", { postId: 1}) | |
* .then(data => { | |
* console.log(data); | |
* }); | |
*/ | |
function getJSON(url, qs_params) { | |
function buildQueryString(params) { | |
return Object.entries(params).map(d => `${d[0]}=${d[1]}`).join('&'); | |
} | |
return new Promise((resolve, reject) => { | |
const qs = qs_params ? '?' + buildQueryString(qs_params) : ''; | |
const xhr = new XMLHttpRequest(); | |
xhr.open('GET', `${url}${qs}`); | |
xhr.onload = function() { | |
if (xhr.status >= 200 && xhr.status < 400) { | |
resolve(JSON.parse(xhr.responseText)); | |
} else { | |
resolve(xhr.responseText); | |
} | |
}; | |
xhr.onerror = () => reject(xhr.statusText); | |
xhr.send(); | |
}); | |
} |