[AJAX] base javascript --> PHP
Bonjour,
Je tente un petit exo pour comprendre comment utiliser l'objet xmlhttprequest. Mon but est simplement de récupérer la largeur de l'écran via javascript puis de l'afficher (ou d'en faire autre chose via PHP éventuellement).
Voici le code de index.php :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
<!DOCTYPE html>
<html>
<header>
<title>titre</title>
<script type="text/javascript" src="funcs.js"></script>
<?php
$width = 0;
if (isset($_GET["width"])) $width = $_GET["width"];
else {
echo '
<script language="JavaScript"> sendScreenWidth() </script>
';
}
?>
</header>
<body>
<?php echo $width; ?>
</body>
</html> |
puis le code de funcs.js : (la création de l'objet xhr étant copié de wikipedia)
Code:
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
|
function createXhrObject()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
if (window.ActiveXObject)
{
var names = [
"Msxml2.XMLHTTP.6.0",
"Msxml2.XMLHTTP.3.0",
"Msxml2.XMLHTTP",
"Microsoft.XMLHTTP"
];
for(var i in names)
{
try{ return new ActiveXObject(names[i]); }
catch(e){}
}
}
window.alert("Votre navigateur ne prend pas en charge l'objet XMLHTTPRequest.");
return null; // non supporté
}
/* tentative 1:
function sendScreenWidth() {
xhr = createXhrObject();
xhr.open("GET","index.php?width="+screen.width,true);
xhr.send(null);
}
*/
// tentative 2 : (marche pas non plus)
function sendScreenWidth() {
xhr = createXhrObject();
xhr.open("GET","index.php",true);
var data = "width="+screen.width;
alert(data); // debug
xhr.send(data);
} |
L'alert() dans la dernière fonction affiche bien ma largeur d'écran, mais l'echo en php persiste à afficher 0.
Merci d'avance !