[AJAX] Récupérer la réponse du serveur dans une fonction
Hep!
J'ai la une petite fonction javascript pour appeler un script php de manière asynchrone (ajax). Mais il semble y avoir un problème de portée avec la variable "respData" : lorsque je fais mon alert dans la fonction onreadystatechange, il affiche bien "contenu script", mais toute la fonction me retourne null quand je l'appelle, alors que j'ai à la fin : return respData;
Quelqu'un voit le prob ?
mon javascript :
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
|
// a function to call a simple php script (ONLY WITH "GET" METHOD FOR THE MOMENT!)
var callPHPScript = function(url){
var XMLHTTP = getXMLHTTP();
var respData = null;
// sending of the request
if(XMLHTTP){
XMLHTTP.open("GET", url, true);
XMLHTTP.send(null);
}
else{
alert("Could not create XMLHTTP object");
}
// action for the response from the server
if (XMLHTTP){
XMLHTTP.onreadystatechange = function(){
if (XMLHTTP.readyState == 4){ // 4 : "complete" state
if (XMLHTTP.status == 200){ // 200 : HTTP Code OK
respData = XMLHTTP.responseText;
alert("answer is : " + respData); // affichera "answer is : contenu script"
}
}
}
}
return respData; // mais ici respData vaut null !
} |
la fonction getXMLHTTP (qui fonctionne sans problème) :
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
|
// get the XMLHTTP object
function getXMLHTTP(){
var xmlhttp = null;
// Conditionnal Compilation for IE */
/*@cc_on
@if (@_jscript_version >= 5){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E){
xmlhttp = null;
}
}
}
@else
xmlhttp = null;
@end @*/
// try to create de http object if it's not done yet
if (xmlhttp == null && typeof XMLHttpRequest != 'undefined'){
try{
xmlhttp = new XMLHttpRequest();
}
catch (e){
xmlhttp = null;
}
}
return xmlhttp;
} |
et le php :
Code:
1 2 3 4
|
<?php
echo "contenu script";
?> |