Simple exercise to learn AJAX [closed]

0

As I want to learn AJAX, I am looking for a very simple "hello world" exercise but on AJAX. Have as few lines of code, if possible as simple as possible. I've googled a bit, and I do not find anything super easy. I've also seen this tutorial on udemy , but I do not know Jquery yet. I have also seen other resources but they relate it to PHP and I do not know PHP either. I would like an exercise that only had javascript, html and css and for now nothing else.

    
asked by Mr. Baldan 12.10.2018 в 09:54
source

1 answer

1

Please read the comments in the code.

function cargar() {
  var xhttp = new XMLHttpRequest();
  // cuando el estado cambie. . . 
  /*
  el valor para readyState puede ser:
  0: UNSENT o sea: sin enviar
  1: OPENED o sea: ha abierto el documento
  2: HEADERS_RECEIVED: enviado y headers recibidos
  3: LOADING: se esta descargando
  4: DONE: ya hay respuesta.


  El estatus puede ser: 
  404: no encontrado
  403: forbidden: prohibido
  . . . .
  200 OK
  */

  xhttp.onreadystatechange = function() {
  // si hay una respuesta y status 200 OK
    if (this.readyState == 4 && this.status == 200) {
      // utiliza el resultado 
      callback(responseText);
      // tambien puedes utilizar responseXML en lugar de responseText si la respuesta que esperas es un XML
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();


  function callback(respuesta){
  // haz algo con esta respuesta:
  console.log(respuesta)
  }
  }
}
    
answered by 12.10.2018 в 10:49