AJAX - Objeto XMLHttpRequest
- Página Anterior Introdução ao AJAX
- Próxima Página Requisição AJAX
O objeto XMLHttpRequest é a base do AJAX.
- Create XMLHttpRequest object
- Define callback function
- Abrir o objeto XMLHttpRequest
- 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();
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.
|
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
|
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
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();
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
|
estado |
Retorna o número do estado da solicitação
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(); }
O evento onreadystatechange foi acionado quatro vezes (1-4), e o readyState mudou uma vez em cada vez.
- Página Anterior Introdução ao AJAX
- Próxima Página Requisição AJAX