Я бы сделал как-то так:
request('http://api.randomuser.me/1.0/', {
results: 50,
nat: ['gb', 'us'],
inc: ['gender', 'name', 'location', 'email', 'phone', 'picture']
}).get(function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
request('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
}).post(function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
function request(link, params, setup) {
return {
get: function (success, error) {
return ajax(extend({}, {
url: link + (params ? '?' + param(params) : ''),
method: 'GET',
success: success || function () {},
error: error || function () {}
}, setup || {}));
},
post: function (success, error) {
return ajax(extend({}, {
url: link,
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
data: params,
success: success || function () {},
error: error || function () {}
}, setup || {}));
}
};
}
function ajax(params) {
var setting = extend({}, {
url: window.location.href,
method: 'GET',
async: true,
data: undefined,
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
success: function (data, xhr, params) {},
error: function (error, xhr, params) {}
}, params || {});
var setHeaders = function (headers) {
for (var name in headers) {
this.setRequestHeader(name, headers[name]);
}
};
var xhr = new XMLHttpRequest();
xhr.open(setting.method, setting.url, setting.async);
setHeaders.call(xhr, setting.headers);
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
var data = (function () {
try {
return JSON.parse(this.response);
} catch (error) {
return this.response;
}
}).call(this);
setting.success(data, this, setting);
} else {
setting.error(this.status, this, setting);
}
}
}
xhr.send(setting.data ? JSON.stringify(setting.data) : null);
return xhr;
}
function param(data) {
var result = '';
for (var name in data) {
result += name + '=' + (Array.isArray(data[name]) ? data[name].join(',') : data[name]) + '&';
}
return result.slice(0, -1);
}
function extend(output) {
output = output || {};
for (var i = 1; i < arguments.length; i++) {
if (!arguments[i]) continue;
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
output[key] = arguments[i][key];
}
}
}
return output;
}
Но если короче, то вот:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.randomuser.me/1.0/?results=50&nat=gb,us&inc=gender,name,location,email,phone,picture', true);
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
console.log('Успех', data);
} else {
console.log('Ошибка', this);
}
}
}
xhr.send(null);