Skip to content

Instantly share code, notes, and snippets.

@murilogteixeira
Last active June 22, 2020 12:51
Show Gist options
  • Save murilogteixeira/ce1b8271487cd0a5638872ade9767b72 to your computer and use it in GitHub Desktop.
Save murilogteixeira/ce1b8271487cd0a5638872ade9767b72 to your computer and use it in GitHub Desktop.
Exemplo de requisição POST e GET usando JavaScript
function performRequest() {
const method = 'POST';
const url = 'api.com.br';
const params = new URLSearchParams({
param1: "param1",
param2: "param2",
}).toString();
const callback = (data) => {
console.log(data);
};
request(method, url, params, callback);
}
function request(method, url, params, callback) {
var ajax = new XMLHttpRequest();
if(method === 'POST' || method === 'post') {
ajax.open(method, url, true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(params);
}
else if (method === 'GET' || method === 'get') {
ajax.open(method, url + '/?' + params, true);
ajax.send();
}
// Cria um evento para receber o retorno.
ajax.onreadystatechange = () => {
// Caso o state seja 4 e o http.status for 200, é porque a requisiçõe deu certo.
if (ajax.readyState == 4 && ajax.status == 200) {
// Retorno do Ajax
var ajaxReturn = ajax.responseText;
var data = JSON.parse(ajaxReturn);
callback(data);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment