2016-11-06 139 views
0

我寫了一個函數,它從php文件中獲取一些數據。當我解析它並使用警告框來顯示它時,它工作正常,但是當我嘗試返回未定義的值時。我不知道爲什麼會發生這種情況Javascript函數返回null

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請求尚未完成設置。 –

回答

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; 
});