Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Como trabalhar com solicitações AJAX com método POST ou GET?

  1. Para quem está tendo dificuldade com requisições AJAX para coletar alguns dados da API com método POST ou GET.
  2. Documentação AJAX: https://www.w3schools.com/js/js_ajax_intro.asp
  3. Codigo GitHub: https://github.com/lipeomiguel/AluraTools/blob/main/Doc/js/Tools/Ajax/ajaxResquest.js
  • CODIGO:
function xmlRequest(method='GET',url='https://api.ipify.org?format=json',asyncCallback=true,callback=false){
  this.method = method;
  this.url = url;
  this.asyncCallback = asyncCallback;
  this.callback = callback;
  this.return = (callback)=>{
      /**
        * ! Check if the callback is being called!
        * ? ajax.return(?);
      **/
      const xml = new XMLHttpRequest();
      xml.open(this.method,this.url,this.asyncCallback);
      xml.send();
      xml.onreadystatechange = ()=>{
        if(xml.readyState == 4){
          callback(xml);
      }
    }
  }
}
const ajax = new xmlRequest();
ajax.return(dados); //? Create callback for data processing: [ ajax.return(a); ] 
function dados(xml){
  console.log(xml.responseText);
}
  • VSCODE SNIPPETS:
"JS AJAX RESQUEST [ GET | POST ]": {
        "prefix": "JSAJAXRESQUEST",
        "body": [
            "function xmlRequest(method='GET',url='https://api.ipify.org?format=json',asyncCallback=true,callback=false){",
            "	this.method = method;",
            "	this.url = url;",
            "	this.asyncCallback = asyncCallback;",
            "	this.callback = callback;",
            "	this.return = (callback)=>{",
            "			/**",
            "				* ! Check if the callback is being called!",
            "				* ? ajax.return(?);",
            "			**/",
            "			const xml = new XMLHttpRequest();",
            "			xml.open(this.method,this.url,this.asyncCallback);",
            "			xml.send();",
            "			xml.onreadystatechange = ()=>{",
            "				if(xml.readyState == 4){",
            "					callback(xml);",
            "			}",
            "		}",
            "	}",
            "}",
            "const ajax = new xmlRequest();",
            "ajax.return($1); //? Create callback for data processing: [ ajax.return(a); ] ",
        ],
        "description": "This AJAX function is used to make simple requests like GET or POST.",
    }

3. ATENÇÃO: SOLICITAÇÕES COM ENVIO DE PARÂMETROS DE HEADER, É NECESSÁRIO TER A DOCUMENTAÇÃO E FAZER ALTERAÇÕES NO CÓDIGO.

1 resposta
solução!

Olá Felipe, tudo bem?

Muito obrigada pela sua valiosa contribuição no fórum sobre como trabalhar com solicitações AJAX utilizando os métodos POST e GET. Sua explicação detalhada e o código fornecido foram extremamente úteis.

A documentação e o exemplo de código no GitHub que você compartilhou são recursos inestimáveis para quem está enfrentando dificuldades com requisições AJAX. A implementação clara e os comentários dentro do código ajudam a entender cada passo do processo.

Agradeço também pela dica sobre a necessidade de alterar o código ao lidar com solicitações que enviam parâmetros no cabeçalho. Esse tipo de detalhe é fundamental para evitar problemas e garantir que as requisições sejam feitas corretamente.

Parabéns pela contribuição e obrigada por compartilhar seu conhecimento com a comunidade!

Um abraço e bons estudos.