Skip to content

Instantly share code, notes, and snippets.

@davidchc
Created January 9, 2019 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidchc/3306bc9f748df924afc134aa2207d7d1 to your computer and use it in GitHub Desktop.
Save davidchc/3306bc9f748df924afc134aa2207d7d1 to your computer and use it in GitHub Desktop.
Exemplo de adicionar carregamento ajax, diretamente pelo manipulador do elemento na tag. Essa abordagem não é interessante pq vc precisa de muitos pontos de alteração, e com isso podendo correr erros.
<h1>Página Home</h1>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<a href="#" onclick="loadPage('home.html')">Home</a>
<div id="content"></div>
<script src="page.js"></script>
</body>
</html>
//Instancia XMLHttpRequest
const ajax = new XMLHttpRequest;
//define quem vai receber o conteudo do ajax
const content = document.querySelector("#content");
//Define a função que fará a inclusão do conteudo
const loadPage = (page) => {
//Abre conexão como GET
ajax.open("GET", page, true);
//faz o envio
ajax.send();
//Verifica se tem mudança do status
ajax.onreadystatechange = () => {
//se for completo
if(ajax.readyState == 4 && ajax.status == 200) {
//add o conteudo da div
content.innerHTML = ajax.responseText;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment