XMLHttpRequest RESTful (GET, POST, PUT, DELETE)
REST

Publicado em: 23/02/2018 00:00:00, por IVAN VARGAS

Encontrei esta página no GitHub e resolvi compartilhar aqui :)

Créditos para EtienneR.

Fonte: https://gist.github.com/EtienneR/2f3ab345df502bd3d13e

// Get all users
var url  = "http://localhost:8080/api/v1/users";
var xhr  = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
	var users = JSON.parse(xhr.responseText);
	if (xhr.readyState == 4 && xhr.status == "200") {
		console.table(users);
	} else {
		console.error(users);
	}
}
xhr.send(null);


// Get a user
var url  = "http://localhost:8080/api/v1/users";
var xhr  = new XMLHttpRequest()
xhr.open('GET', url+'/1', true)
xhr.onload = function () {
	var users = JSON.parse(xhr.responseText);
	if (xhr.readyState == 4 && xhr.status == "200") {
		console.table(users);
	} else {
		console.error(users);
	}
}
xhr.send(null);


// Post a user
var url = "http://localhost:8080/api/v1/users";

var data = {};
data.firstname = "John";
data.lastname  = "Snow";
var json = JSON.stringify(data);

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
	var users = JSON.parse(xhr.responseText);
	if (xhr.readyState == 4 && xhr.status == "201") {
		console.table(users);
	} else {
		console.error(users);
	}
}
xhr.send(json);


// Update a user
var url = "http://localhost:8080/api/v1/users";

var data = {};
data.firstname = "John2";
data.lastname  = "Snow2";
var json = JSON.stringify(data);

var xhr = new XMLHttpRequest();
xhr.open("PUT", url+'/12', true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
	var users = JSON.parse(xhr.responseText);
	if (xhr.readyState == 4 && xhr.status == "200") {
		console.table(users);
	} else {
		console.error(users);
	}
}
xhr.send(json);


// Delete a user
var url = "http://localhost:8080/api/v1/users";
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url+'/12', true);
xhr.onload = function () {
	var users = JSON.parse(xhr.responseText);
	if (xhr.readyState == 4 && xhr.status == "200") {
		console.table(users);
	} else {
		console.error(users);
	}
}
xhr.send(null);


IS5 TECNOLOGIA

São Lourenço do Sul/RS
Telefone: (53)9963-5721
E-mail: contato@is5.com.br
Facebook: fb.com/is5tecnologia
Skype: ivan_is5
GitHub: github.com/isvargas
O QUE FAZEMOS

Automação Comercial
Desenvolvimento de Sistemas
Hospedagem e Desenvolvimento de Sites
Aplicativos Mobile
Consultoria e Projetos Freelancer
Desenvolvido por is5 tecnologia