|<- [[jet:Introduction to regular expressions]]|[[jet:Working with objects and prototypes]] ->|
AJAX = Asynchronous Javascript and XML
XML = not required
AJAX == JavaScript
- Créer une requête
- 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==
This is an AJAX Example
==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);
//....