Introduction to regular expressionsWorking with objects and prototypes

AJAX = Asynchronous Javascript and XML

XML = not required

AJAX == JavaScript

  1. Créer une requête
  2. Gérer la réponse
// 1. créer la requête
var myRequest = new XMLHttpRequest();
// En vrai on vérifie d'abord que c'est possible :
var myRequest;
if (window.XMLHttpRequest) {
  var myRequest = new XMLHttpRequest();
} else if (winow.ActiveXObject) { // IE
  myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2. la réponse
myrequest.onreadystatechange = function(){ //event ! souvent firé !
  console.log("We were called!"); // code lors des réponses
};
// ensuite on configure et on envoie
myRequest.open("GET","http://mysite.com/somedata.php",true); // true = asynchrone
myRequest.send(null);

Exemple

AjaxExample.html
<!DOCTYPE html>
<html>
	<head>
		<title></title>
	</head>
	<body>
	<div id="mainContent">
    <h1>This is an AJAX Example</h1>
	</div>
    
    <script src="script.js"></script>
	</body>
</html>
script.js
// Simple Ajax example.

// 1: Create the request 
var myRequest;

// feature check!
if (window.XMLHttpRequest) {  // does it exist? we're in Firefox, Safari etc.
    myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // if not, we're in IE
    myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

// 2: create an event handler for our request to call back
myRequest.onreadystatechange = function(){
    console.log("We were called!");
    console.log(myRequest.readyState);
    if (myRequest.readyState === 4) {
        var p = document.createElement("p");
        var t = document.createTextNode(myRequest.responseText);
        p.appendChild(t);
        document.getElementById("mainContent").appendChild(p);
    }
};

// open and send it
myRequest.open('GET', 'simple.txt', true);
// any parameters?
myRequest.send(null);

//....