AJAX - Objeto XMLHttpRequest

O objeto XMLHttpRequest é a base do AJAX.

  1. Create XMLHttpRequest object
  2. Define callback function
  3. Abrir o objeto XMLHttpRequest
  4. Enviar solicitações para o servidor

XMLHttpRequest object

Todos os navegadores modernos suportam XMLHttpRequest object.

O objeto XMLHttpRequest pode ser usado para trocar dados com o servidor web em segundo plano. Isso significa que é possível atualizar parte do conteúdo da página sem recarregar toda a página.

Create XMLHttpRequest object

All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have built-in XMLHttpRequest object.

Syntax for creating XMLHttpRequest object:

variable = new XMLHttpRequest();

Define callback function

A callback function is a function that is passed as a parameter to another function.

In this case, the callback function should contain the code to be executed when the response is ready.

xhttp.onload = function() {
  // What to do when the response is ready
}

Send request

To send a request to the server, you can use the XMLHttpRequest object's open() And send() Method:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Exemplo

// Create XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define callback function
xhttp.onload = function() {
  // You can use data here
}
// Send request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Experimente você mesmo

Cross-Domain Access (Access Across Domains)

For security reasons, modern browsers do not allow cross-domain access.

This means that the web page and the XML file it tries to load must be on the same server.

The examples on CodeW3C.com all open XML files located in the CodeW3C.com domain.

If you want to use the above example on one of your web pages, the XML file you load must be located on your own server.

XMLHttpRequest object methods

Method Descrição
new XMLHttpRequest() Create a new XMLHttpRequest object.
abort() Cancel the current request.
getAllResponseHeaders() Return header information.
getResponseHeader() Return specific header information.
open(method, url, async, user, psw)

Specify the request.

  • method: request type GET or POST
  • url: file location
  • async: true (asynchronous) or false (synchronous)
  • user: optional username
  • psw: optional password
send() Send a request to the server, used for GET requests.
send(string) Send a request to the server, used for POST requests.
setRequestHeader() Add a label/value pair to the headers to be sent.

XMLHttpRequest object properties

Atributo Descrição
onload Define the function to be called when a (loading) request is received.
onreadystatechange Define the function to be called when the readyState attribute changes.
readyState

Salva o estado do XMLHttpRequest

  • 0: Solicitação não inicializada
  • 1: Conexão do servidor estabelecida
  • 2: Solicitação recebida
  • 3: Processando a solicitação
  • 4: A solicitação foi concluída e a resposta está pronta
responseText Retorna os dados da resposta em formato de string
responseXML Retorna os dados da resposta em formato XML
estado

Retorna o número do estado da solicitação

  • 200: "OK"
  • 403: "Proibido"
  • 404: "Não Encontrado"

Para lista completa, acesse Manual de referência de mensagens HTTP

statusText Retorna o texto do estado (por exemplo, "OK" ou "Not Found")

Atributo onload

Ao usar o XMLHttpRequest, você pode definir uma função de callback para ser executada quando a resposta for recebida

Defina a função no objeto XMLHttpRequest onload A função é definida no atributo

Exemplo

xhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Experimente você mesmo

Múltiplos callbacks

Se houver várias tarefas AJAX no site, deve ser criada uma função para executar o XMLHttpRequest e uma função de callback para cada tarefa AJAX

A chamada da função deve conter a URL e a função a ser chamada quando a resposta estiver pronta

Exemplo

loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {cFunction(this);}
  xhttp.open("GET", url);
  xhttp.send();
}
function myFunction1(xhttp) {
  // Aqui está a ação
}
function myFunction2(xhttp) {
  // Aqui está a ação
}

Atributo onload

readyState Atributo salva o estado do XMLHttpRequest

onreadystatechange Atributo define uma função de callback que é executada quando o readyState mudar

estado Atributo e statusText Atributo salva o estado do XMLHttpRequest

Atributo Descrição
onreadystatechange Define a função a ser chamada quando o atributo readyState mudar
readyState

Salva o estado do XMLHttpRequest

  • 0: Solicitação não inicializada
  • 1: Conexão do servidor estabelecida
  • 2: Solicitação recebida
  • 3: Processando a solicitação
  • 4: A solicitação foi concluída e a resposta está pronta
estado

Retorna o número do estado da solicitação

  • 200: "OK"
  • 403: "Proibido"
  • 404: "Não Encontrado"

Para lista completa, acesse Manual de referência de mensagens HTTP

statusText statusText

Retorna o texto de estado (por exemplo, "OK" ou "Not Found").

A função onreadystatechange é chamada sempre que o readyState mudar. 4 e o status for 200 Quando a resposta estiver pronta:

Exemplo

function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt");
  xhttp.send();
}

Experimente você mesmo

O evento onreadystatechange foi acionado quatro vezes (1-4), e o readyState mudou uma vez em cada vez.