I have been searching for a non-JQuery AJAX function that can fetch data from a URL and return it as a JSON object.
For example, let's say I want to display information about Users from one JSON located at URL1 and also include information about Posts from another JSON located at URL2 in the same display.
I would like to achieve this without using JQuery.
Here is an example of how I envision this:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
function getInfo(){
var users, posts;
loadJSON('http://.com/users',
function(dataU) {
users = dataU;
},
function(xhr) { console.error(xhr); }
);
loadJSON('http://.com/posts',
function(dataP) {
posts = dataP;
},
function(xhr) { console.error(xhr); }
);
console.log(users);
console.log(posts);
}
getInfo();