Ejemplo de código JavaScript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<body>

<div id="ejemplo">
<h2>Ejemplo AJAX</h2>
<button type="button" onclick="cargarDoc()">Cambiar contenido</button>
</div>

<script>
function cargarDoc() {
  // Declaración de objeto XMLHttpRequest
  var xhttp = new XMLHttpRequest(); 
  // Configuración de la operación va a realizar el cliente, una vez reciba respuesta del servidor.
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("ejemplo").innerHTML =
      this.responseText;
    }
  };
  // Configura la petición, indicando el método HTTP, el recurso del servidor, y tipo de comunicación asincrónica (true) o sincrónica (false).
  xhttp.open("GET", "ajax_info.txt", true);
  // Envía la petición.
  xhttp.send();
}
</script>

</body>
</html>