|
Mise à jour : 07/12/2010
Difficulté :
Intermédiaire
5 614 visites depuis 7 jours, dont 1 368 sur ce chapitre, classé 34/795
|
![]() Méthode | ![]() Internet Explorer | ![]() Firefox | ![]() Opera | ![]() Google Chrome | ![]() Safari |
|---|---|---|---|---|---|
| XMLHttpRequest | Oui avec ActiveX pour IE < 7 |
Oui |
Oui |
Oui |
Oui |
1 | var xhr = new XMLHttpRequest(); |
1 2 3 4 5 | try { var xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { var xhr = new ActiveXObject("Microsoft.XMLHTTP"); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var xhr = null; if (window.XMLHttpRequest || window.ActiveXObject) { if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } else { xhr = new XMLHttpRequest(); } } else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function getXMLHttpRequest() { var xhr = null; if (window.XMLHttpRequest || window.ActiveXObject) { if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } else { xhr = new XMLHttpRequest(); } } else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; } return xhr; } |
1 | var xhr = getXMLHttpRequest(); |
1 2 3 4 | var xhr = getXMLHttpRequest(); // Voyez la fonction getXMLHttpRequest() définie dans la partie précédente xhr.open("GET", "handlingData.php", true); xhr.send(null); |
1 | xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); |
1 2 | xhr.open("GET", "handlingData.php?variable1=truc&variable2=bidule", true); xhr.send(null); |
1 2 3 | xhr.open("POST", "handlingData.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("variable1=truc&variable2=bidule"); |
1 2 3 4 5 | var sVar1 = encodeURIComponent("contenu avec des espaces"); var sVar2 = encodeURIComponent("je vois que vous êtes un bon élève... oopa !"); xhr.open("GET", "handlingData.php?variable1=" + sVar1 + "&variable2= " + sVar2, true); xhr.send(null); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php header("Content-Type: text/plain"); // Utilisation d'un header pour spécifier le type de contenu de la page. Ici, il s'agit juste de texte brut (text/plain). $variable1 = (isset($_GET["variable1"])) ? $_GET["variable1"] : NULL; $variable2 = (isset($_GET["variable2"])) ? $_GET["variable2"] : NULL; if ($variable1 && $variable2) { // Faire quelque chose... echo "OK"; } else { echo "FAIL"; } ?> |
1 2 3 4 5 6 7 8 9 10 | var xhr = getXMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { alert("OK"); // C'est bon \o/ } }; xhr.open("GET", "handlingData.php", true); xhr.send(null); |
1 2 3 4 5 | xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { alert(xhr.responseText); // Données textuelles récupérées } }; |
1 2 3 4 5 6 7 8 9 10 11 12 | function funcA(callback) { // instruction... // instruction... // instruction... callback(); } function funcB() { alert("Plop"); } funcA(funcB); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function request(callback) { var xhr = getXMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { callback(xhr.responseText); } }; xhr.open("GET", "handlingData.php", true); xhr.send(null); } function readData(sData) { // On peut maintenant traiter les données sans encombrer l'objet XHR. if (sData == "OK") { alert("C'est bon"); } else { alert("Y'a eu un problème"); } } request(readData); |
1 2 3 4 5 6 7 8 9 | <?xml version="1.0" encoding="utf-8"?> <!-- XMLHttpRequest_getXML.xml --> <root> <soft name="Adobe Dreamweaver" /> <soft name="Microsoft Expression Web" /> <soft name="Notepad++" /> <soft name="gedit" /> <soft name="Emacs" /> </root> |
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Techniques AJAX - XMLHttpRequest</title> <script type="text/javascript" src="oXHR.js"></script> <script type="text/javascript"> <!-- function request(callback) { var xhr = getXMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { callback(xhr.responseXML); } }; xhr.open("GET", "XMLHttpRequest_getXML.xml", true); xhr.send(null); } function readData(oData) { var nodes = oData.getElementsByTagName("soft"); var ol = document.createElement("ol"), li, cn; for (var i=0, c=nodes.length; i<c; i++) { li = document.createElement("li"); cn = document.createTextNode(nodes[i].getAttribute("name")); li.appendChild(cn); ol.appendChild(li); } document.getElementById("output").appendChild(ol); } //--> </script> </head> <body> <p> <button onclick="request(readData);">Afficher le fichier XML</button> <div id="output"></div> </p> </body> </html> |
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Techniques AJAX - XMLHttpRequest</title> <script type="text/javascript" src="oXHR.js"></script> <script type="text/javascript"> <!-- function request(callback) { var xhr = getXMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { callback(xhr.responseText); } }; var nick = encodeURIComponent(document.getElementById("nick").value); var name = encodeURIComponent(document.getElementById("name").value); xhr.open("GET", "XMLHttpRequest_getString.php?Nick=" + nick + "&Name=" + name, true); xhr.send(null); } function readData(sData) { alert(sData); } //--> </script> </head> <body> <form> <p> <label for="nick">Pseudo :</label> <input type="text" id="nick" /><br /> <label for="name">Prénom :</label> <input type="text" id="name" /> </p> <p> <input type="button" onclick="request(readData);" value="Exécuter" /> </p> </form> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php header("Content-Type: text/plain"); $nick = (isset($_GET["Nick"])) ? $_GET["Nick"] : NULL; $name = (isset($_GET["Name"])) ? $_GET["Name"] : NULL; if ($nick && $name) { echo "Bonjour " . $name . " ! Je vois que votre pseudo est " . $nick; } else { echo "FAIL"; } ?> |
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Techniques AJAX - XMLHttpRequest</title> <script type="text/javascript" src="oXHR.js"></script> <script type="text/javascript"> <!-- function request(callback) { var sleep = document.getElementById("sleep").value; if (isNaN(parseInt(sleep))) { alert(sleep + " n'est pas un nombre valide !"); return; } var xhr = getXMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { callback(xhr.responseText); document.getElementById("loader").style.display = "none"; } else if (xhr.readyState < 4) { document.getElementById("loader").style.display = "inline"; } }; xhr.open("GET", "XMLHttpRequest_getSleep.php?Sleep=" + sleep, true); xhr.send(null); } function readData(sData) { alert(sData); } //--> </script> </head> <body> <form> <p> <label for="sleep">Temps de sommeil :</label> <input type="text" id="sleep" /> </p> <p> <input type="button" onclick="request(readData);" value="Exécuter" /> <span id="loader" style="display: none;"><img src="loader.gif" alt="loading" /></span> </p> </form> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php header("Content-Type: text/plain"); $sleep = (isset($_GET["Sleep"])) ? $_GET["Sleep"] : NULL; echo date("h:i:s") . "\n\n"; if ($sleep) { sleep($sleep); echo $sleep . "\n\n"; } else { sleep(10); echo "10\n\n"; } echo date("h:i:s") . "\n"; ?> |
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 | <?php header("Content-Type: text/plain"); $sleep = (isset($_GET["Sleep"])) ? $_GET["Sleep"] : NULL; echo date("h:i:s") . "\n\n"; if ($sleep) { fsleep($sleep); echo $sleep . "\n\n"; } else { fsleep(10); echo "10\n\n"; } echo date("h:i:s") . "\n"; function fsleep($sec) { // Pour chez Free $sec = abs((int) $sec) ; $tps = time(); while ($tps + $sec >= time()) ; } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var xhr = null; function request(callback) { if (xhr && xhr.readyState != 0) { xhr.abort(); // On annule la requête en cours ! } xhr = getXMLHttpRequest(); // plus de mot clé 'var' xhr.onreadystatechange = function() { /* ... */ }; xhr.open("GET", "XMLHttpRequest_getSleep.php?Sleep=" + sleep, true); xhr.send(null); } |
1 2 3 4 5 6 7 8 9 10 11 12 | var xhr = null; function request(callback) { if (xhr && xhr.readyState != 0) { alert("Attendez que la requête ait abouti avant de faire joujou"); return; } xhr = getXMLHttpRequest(); /* ... */ } |
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 30 31 32 33 34 35 36 37 38 39 40 41 42 | CREATE TABLE IF NOT EXISTS `ajax_example_editors` ( `id` tinyint(4) NOT NULL AUTO_INCREMENT, `name` varchar(50) collate latin1_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=7 ; INSERT INTO `ajax_example_editors` (`id`, `name`) VALUES (1, 'Adobe'), (2, 'Macromedia'), (3, 'Microsoft'), (4, 'Mozilla'), (5, 'ACDSystem'), (6, 'Apple'); CREATE TABLE IF NOT EXISTS `ajax_example_softwares` ( `id` tinyint(4) NOT NULL AUTO_INCREMENT, `name` varchar(50) collate latin1_general_ci NOT NULL, `idEditor` tinyint(4) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=21 ; INSERT INTO `ajax_example_softwares` (`id`, `name`, `idEditor`) VALUES (1, 'Photoshop', 1), (2, 'GoLive', 1), (3, 'InDesign', 1), (4, 'Acrobat', 1), (5, 'Dreamweaver', 2), (6, 'Flash', 2), (7, 'ColdFusion', 2), (8, 'FlashPaper', 2), (9, 'Silverlight', 3), (10, 'Internet Explorer', 3), (11, 'Office', 3), (12, 'Visual Studio', 3), (13, 'Camino', 4), (14, 'Firefox', 4), (15, 'Rhino', 4), (16, 'Thunderbird', 4), (17, 'ACDSee Photo Editor', 5), (18, 'ACDSee Photo Manager', 5), (19, 'iTunes', 6), (20, 'Safari for Windows', 6); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <div id="programBox"> <p id="editors"> <select id="editorsSelect" onchange="request(this);"> <option value="none">Selection</option> <?php mysql_connect($hote, $login, $m_d_p); mysql_select_db($bdd); $query = mysql_query("SELECT * FROM ajax_example_editors ORDER BY name"); while ($back = mysql_fetch_assoc($query)) { echo "\t\t\t\t<option value=\"" . $back["id"] . "\">" . $back["name"] . "</option>\n"; } ?> </select> <span id="loader" style="display: none;"><img src="images/loader.gif" alt="loading" /></span> </p> <p id="softwares"> <select id="softwaresSelect"></select> </p> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function request(oSelect) { var value = oSelect.options[oSelect.selectedIndex].value; var xhr = getXMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { readData(xhr.responseXML); document.getElementById("loader").style.display = "none"; } else if (xhr.readyState < 4) { document.getElementById("loader").style.display = "inline"; } }; xhr.open("POST", "XMLHttpRequest_getListData.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("IdEditor=" + value); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php header("Content-Type: text/xml"); echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; echo "<list>"; $idEditor = (isset($_POST["IdEditor"])) ? htmlentities($_POST["IdEditor"]) : NULL; if ($idEditor) { mysql_connect($hote, $login, $m_d_p); mysql_select_db($bdd); $query = mysql_query("SELECT * FROM ajax_example_softwares WHERE idEditor=" . mysql_real_escape_string($idEditor) . " ORDER BY name"); while ($back = mysql_fetch_assoc($query)) { echo "<item id=\"" . $back["id"] . "\" name=\"" . $back["name"] . "\" />"; } } echo "</list>"; ?> |
1 2 3 | <?php header("Content-Type: text/xml"); ?> |
1 2 3 4 5 6 | <?xml version="1.0" encoding="utf-8"?> <list> <item id="0" name="Programme A" /> <item id="1" name="programme B" /> ... </list> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function readData(oData) { var nodes = oData.getElementsByTagName("item"); var oSelect = document.getElementById("softwaresSelect"); var oOption, oInner; oSelect.innerHTML = ""; for (var i=0, c=nodes.length; i<c; i++) { oOption = document.createElement("option"); oInner = document.createTextNode(nodes[i].getAttribute("name")); oOption.value = nodes[i].getAttribute("id"); oOption.appendChild(oInner); oSelect.appendChild(oOption); } } |
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Techniques AJAX - XMLHttpRequest</title> <script type="text/javascript" src="oXHR.js"></script> <script type="text/javascript"> <!-- function request(oSelect) { var value = oSelect.options[oSelect.selectedIndex].value; var xhr = getXMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { readData(xhr.responseXML); document.getElementById("loader").style.display = "none"; } else if (xhr.readyState < 4) { document.getElementById("loader").style.display = "inline"; } }; xhr.open("POST", "XMLHttpRequest_getListData.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("IdEditor=" + value); } function readData(oData) { var nodes = oData.getElementsByTagName("item"); var oSelect = document.getElementById("softwaresSelect"); var oOption, oInner; oSelect.innerHTML = ""; for (var i=0, c=nodes.length; i<c; i++) { oOption = document.createElement("option"); oInner = document.createTextNode(nodes[i].getAttribute("name")); oOption.value = nodes[i].getAttribute("id"); oOption.appendChild(oInner); oSelect.appendChild(oOption); } } //--> </script> </head> <body> <fieldset> <legend>Programmes</legend> <div id="programBox"> <p id="editors"> <select id="editorsSelect" onchange="request(this);"> <option value="none">Selection</option> <?php mysql_connect($hote, $login, $m_d_p); mysql_select_db($bdd); $query = mysql_query("SELECT * FROM ajax_example_editors ORDER BY name"); while ($back = mysql_fetch_assoc($query)) { echo "\t\t\t\t<option value=\"" . $back["id"] . "\">" . $back["name"] . "</option>\n"; } ?> </select> <span id="loader" style="display: none;"><img src="images/loader.gif" alt="loading" /></span> </p> <p id="softwares"> <select id="softwaresSelect"></select> </p> </div> </fieldset> </body> </html> |
| Disponibilité | Description | |
|---|---|---|
| onreadystatechange | Tous | Propriété exécutée à chaque changement d'état de la requête |
| readyState | Tous | Etat de la requête, à vérifier au sein du onreadystatechange pour savoir où en est le traitement de la requête |
| responseText | Tous | Réponse du serveur, au format texte |
| responseXML | Tous | Réponse du serveur, au format XML |
| status | Tous | Code de réponse du serveur (200, 404, 500...) |
| statusText | Tous | Le message associé à status |
| timeout | IE8, non-W3C | Permet de définir un time-out |
| Disponibilité | Description | |
|---|---|---|
| abort | Tous | Annule la requête en cours d'exécution |
| getAllResponseHeaders | Tous - IE7 | Récupère la liste complète des en-têtes de la requête |
| getResponseHeader | Tous - IE7 | Récupère l'en-tête de la requête |
| open | Tous | Définit les modalités d'envoi de la requête |
| overrideMimeType | Tous sauf IE, non-W3C | Permet de forcer le type MIME de la requête |
| send | Tous | Envoie la requête |
| setRequestHeader | Tous | Ajoute un en-tête HTTP manuellement |