2016-11-06 7 views
0

PHPファイルからデータを取得する関数を作成しました。私はそれを解析し、警告ボックスを使って表示するとうまくいきますが、値を返そうとすると、定義されていません。この出来事nullを返すJavascript関数

function getUser() { 

    var httpRequest = new createAjaxRequestObject(); 

    httpRequest.open('GET', 'getUser.php', true); 
    var name; 

    httpRequest.onreadystatechange = function() { 

     if (httpRequest.readyState == 4) { 

      if (httpRequest.status == 200) { 
       name = JSON.parse(httpRequest.responseText); 
       alert(name); //this works just fine and display the name john 
      } else { 
       alert('Problem with request'); 
      } 
     } 
    } 

    httpRequest.send(); 
    return name; //however this is returning null 
} 
+0

Ajaxは非同期です - あなたは名前の変数が、Ajaxリクエストを返していますそれを設定することはまだ完了していません。 –

答えて

3

は今、それがヌル送信し、なぜそれが、すぐhttpRequest.send();が呼び出されるよう値を取るので、私は、見当がつかない。あなたは戻り値にこのような

変更を受け取る関数へのコールバックを渡す必要があり、この場合には

function foo(callback) { 
    httpRequest = new XMLHttpRequest(); 
    httpRequest.onreadystatechange = function() { 
     if (httpRequest.readyState === 4) { // request is done 
      if (httpRequest.status === 200) { // successfully 
       callback(httpRequest.responseText); // we're calling our method 


      } 
     } 
    }; 
    httpRequest.open('GET', 'getUser.php', true); 
    httpRequest.send(); 
} 

foo(function (result) { 
    var name = result; 
}); 
関連する問題