Script ip : Récupérer l'ip en JavaScript avec AJAX
Comment afficher l'adresse IP en JavaScript ave cun appel AJAX
Partie II : L'interactivité
Edition 1 | Chapitre 14 : Les appels AJAX / Page 224
Edition 2 | Chapitre 14 : Les appels AJAX / Page 240
Edition 3 | Chapitre 14 : Les appels AJAX / Page 240
Exécution du script
Code source
<html><head> <title>Adresse IP en JavaScript</title></head><body><h1 id="monH1">Votre adresse IP affichée en JavaScript</h1> <div id="ip">?</div> <script type="text/javascript">/* Récupération de l'adresse IP de l'utilisateur */function getIP() { var ajax = new XMLHttpRequest(); ajax.onload = function() { console.log("Appel AJAX terminé"); console.log(" status : "+this.status); console.log(" response : "+this.response); if (this.status == 200) { /* Le service a bien répondu */ var ip=this.response; var reg=new RegExp("^[0-9]{1,3}.+[0-9]{1,3}.+[0-9]{1,3}.+[0-9]{1,3}$") if (reg.test(ip)) { document.getElementById("ip").innerHTML=ip; } else { document.getElementById("ip").innerHTML="Erreur retour"; } } } /* Préparation de la requête et envoi */ var url="/api/get-my-ip.php"; ajax.open("GET", url, true); ajax.send();}getIP();</script></body><style type="text/css"> div#ip { margin: 5px; padding: 5px; font-size: 30px; line-height: 60px; min-height:60px; font-weight: bold; border:1px solid #ccc; border-radius:5px; width:250px; margin-left:auto; margin-right:auto; padding-top:0px; text-align: center; position: relative; }</style></html>
Troisième édition Tout JavaScript chez Dunod
En savoir plusSortie le 4 janvier 2023
Version papier 29€90
Format électronique 22€99.
Commandez en ligne Le graph des objets JavaScript
Chargement
en cours...